powershell - Pester Should -Throw 不会捕获错误

标签 powershell pester pester-5

这与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/

相关文章:

windows - Pester 5 变量作用域问题 - BeforeDiscovery/It

powershell - 通过 .cmd 文件安装 "azure-powershell.0.8.7.msi"时出现错误

xml - XML子树-仅选择指定的子节点,但与父节点一起选择

c# - 如何使用 PowerShell 远程处理从 C# 向 Active Directory 用户添加图像?

python - 从 Python 运行 PowerShell 脚本

linux - Powershell 无法在 VSCode Linux 上找到类型 [Pester.OutputTypes]

powershell - 使用 -ParameterFilter 时未调用 Get-Date 的纠缠模拟

powershell - 如何在 Pester 测试中模拟 Read-Host?