Search code examples
powershellpester

How to specify what to do if a Pester assertion fails?


If you wanted to say, 1 should equal 1, and if it doesn't then break, what would be the most eloquent way to do this in powershell with pester avoid code duplication?

Eg

{1 | should be 1} else {break}

rather than

1 | should be 1
if (1 -ne 1) {break}

Solution

  • There's no built in functionality for breaking the test execution when a failure occurs at the moment, but it has been discussed here: https://github.com/pester/Pester/issues/360 with some wrokarounds such as this one:

    BeforeEach {
        $FailedCount =  InModuleScope -ModuleName Pester { $Pester.FailedCount }
    
        if ($FailedCount -gt 0) {
            Set-ItResult -Skipped -Because 'previous test failed'
        }
    }
    

    Another option might be to break your tests up into several different Pester scripts. Then you could have some high level or initial tests that you check for success on first and if they have not all passed then you skip execution of the remaining test scripts.

    For example:

    $Failed = (Invoke-Pester -Path First.tests.ps1 -PassThru).FailedCount
    
    If ($Failed -eq 0) {
        Invoke-Pester -Path Second.tests.ps1
        ..
    }