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
相关产品推荐
相关产品推荐

