You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pester 5.4.0中验证特定异常类型抛出的测试失败求解

解决Pester测试无法捕获Get-Service异常的问题

你的测试失败的核心原因是:Get-Service找不到服务时默认抛出的是非终止错误,而Pester的Should -Throw只识别终止异常。

修正后的测试脚本

只需给Get-Service添加-ErrorAction Stop参数,将非终止错误转为终止异常,Pester就能正确捕获:

Import-Module Pester -RequiredVersion 5.4.0

Describe "Testing if a service is registered." {
    It "This service should not be registered in the Windows Services app." {
        { Get-Service -Name "this service does not exist" -ErrorAction Stop } | Should -Throw -ExceptionType ([Microsoft.PowerShell.Commands.ServiceCommandException])
    }
}

原理说明

  • PowerShell中多数命令的错误默认分为两种:非终止错误(仅写入错误流,不中断执行)和终止错误(抛出异常,中断执行)。
  • Get-Service找不到服务时属于前者,所以你的脚本块执行时并没有抛出Pester能识别的终止异常,导致测试失败。
  • -ErrorAction Stop参数强制将该错误转换为终止的ServiceCommandException,符合Should -Throw的捕获条件。

替代写法

也可以在脚本块内临时修改全局错误偏好变量,效果相同:

{ 
    $ErrorActionPreference = 'Stop'
    Get-Service -Name "this service does not exist" 
} | Should -Throw -ExceptionType ([Microsoft.PowerShell.Commands.ServiceCommandException])

额外验证点

执行Get-Module Pester确认已正确加载5.4.0版本,避免版本不匹配导致的语法问题。

内容的提问来源于stack exchange,提问作者hyt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 05:20:27