这与this相同的问题和解决方案,但有更简单的示例,希望更容易找到,因为我花了几个小时才找到上述问题。
我想测试以下代码:
Test-Function(){
{...}
if($ExitCode -ne 0){
throw "Stopped with exit code $ExitCode"
}
}
我正在尝试使用它来测试它:
It "Testing"{
Test-Function -Bad "Params" | Should -Throw
}
当我运行此程序时,出现以下错误:
[-] Testing 1.03s (1.03s|2ms)
RuntimeException: Stopped with exit code 10
At Test-Function {...}
我已经尝试使用 Should -Throw
中的确切错误消息并使用 Write-Error 而不是抛出。这些都不适合我
最佳答案
测试 Should -Throw
时,代码必须位于脚本 block 内,因此它应如下所示:
It "Testing"{
{Test-Function -Bad "Params"} | Should -Throw
}
关于powershell - Pester Should -Throw 不会捕获错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71981844/