|
Given this code: Describe 'ExitCodes' {
It 'Should catch exit codes with $? variable' {
Mock git -Verifiable -MockWith {
# This mock should call through to the real git command. Imagine it transforms some arguments.
& (Get-Command -CommandType Application git) $args
}
& (Get-Command -CommandType Application git) --git-dir ~/missing/.git --work-tree ~/missing/.git/.. status
$? | Should -BeFalse # Works
$LASTEXITCODE | Should -Be 128
git --git-dir ~/missing/.git --work-tree ~/missing/.git/.. status
$? | Should -BeFalse # Breaks
$LASTEXITCODE | Should -Be 128
}
}How can we have the second example, which uses the mock, to work as expected? So that the Pester 5.7.1 and PowerShell 7.4.6 Edit: Remove-Alias -Name git -ErrorAction Ignore
function git {
[CmdletBinding()]
param (
[Parameter(ValueFromRemainingArguments = $true)]
[string[]] $args
)
& (Get-Command -CommandType Application git) $args
if (!$? -OR $LASTEXITCODE -ne 0) {
$PSCmdlet.WriteError([System.Management.Automation.ErrorRecord]::new(
"Wrapped command failed with exit code $LASTEXITCODE",
"WrappedCommandFailed",
[System.Management.Automation.ErrorCategory]::InvalidOperation,
$args
))
}
} |
Replies: 1 comment
|
function f { & /bin/sh -c 'exit 128' }
f
$? # True
$LASTEXITCODE # 128
To get Tested with Pester 6.1.0 on PowerShell 7.5.5. |
$?tells you if the last command succeeded, and a mock is a function, so it stays true as long as the function itself does not fail. This is not specific to mocking, a plain function does the same:$LASTEXITCODEpropagates fine, so assert on that.To get
$?false the mock would have to write an error, and that does not really work here.Write-Errorin-MockWithdoes not flip it, and$PSCmdletis$nullinside the mock body so theWriteErrorfrom your edit is not available.throwdoes flip it, but it is terminating so probably not what you want.Tested with Pester 6.1.0 on PowerShell 7.5.5.