Search code examples
powershellpester

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?


Solution

  • 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 :)