Bernardo
Bernardo

Reputation: 103

Is there a way to mock an $? return using Pester?

I'm writing tests for a PowerShell application, using Pester.

I have been able to create mocks for most functions, but I haven't been able to mock a function returning the $? variable. I'm currently using it to evaluate the returns from AWS CLI commands.

This is, for example, to mock a failing AWS CLI command return.

Any thoughts?

Upvotes: 1

Views: 868

Answers (3)

Bernardo
Bernardo

Reputation: 103

We created an auxiliary function and passed the $? value.

function Test-LastExitCodeIsFalse ($last_exit) {
    if ($last_exit) {
       return $false
    }
    $true
}

And a usage being

aws s3 <an aws command>
if (Test-LastExitCodeIsFalse($?)) {
   throw "AWS Exception"
}

Using Pester, then we just mock the Test-LastExitCodeIsFalse function to return false. And we have a unit test with a failing AWS instance :)

Upvotes: 1

colsw
colsw

Reputation: 3336

If you're looking to get mock code which performs the same function as $?, you can use something like this (it is quite limited in terms of how it actually returns if multiple lines are executed at once, etc., and it will likely need to be modified depending on the execution context):

Function Test-LastCommandError {
    $LastCommand = (History | Select -Last 1).CommandLine
    $LastError = $Error[-1].InvocationInfo.Line
    $LastCommand -eq $LastError
}

1/1#Success
Test-LastCommandError # Returns false

1/0#Error
Test-LastCommandError # Returns true

This works for me manually executing each line, but not in an ad-hoc ISE window (since it copy-pastes everything as one command on execute).

Upvotes: 2

Ben Richards
Ben Richards

Reputation: 3575

You should be able to do:

Mock AWC-CLI { $ = $true } -Verifiable

Upvotes: 0

Related Questions