Search code examples
powershellpesterpester-5

Pester Should -Throw does not catch error


This is the same problem and solution as this, but with simpler examples and hopefully easier to find, since it took me hours to find the above question.

I have the following code that I want to test:

Test-Function(){
  {...}
  if($ExitCode -ne 0){
    throw "Stopped with exit code $ExitCode"
  }
}

I am trying to test it using this:

It "Testing"{
  Test-Function -Bad "Params" | Should -Throw
}

When I run this, I get the following error:

   [-] Testing 1.03s (1.03s|2ms)
    RuntimeException: Stopped with exit code 10
    At Test-Function {...}

I already tried using the exact error message in Should -Throw and using Write-Error instead of throwing. None of those worked for me


Solution

  • When testing for Should -Throw, the code must be inside of a script block, so it should look like this:

    It "Testing"{
      {Test-Function -Bad "Params"} | Should -Throw
    }