如果 Pester 断言失败,如何指定要做什么?

How to specify what to do if a Pester assertion fails?

如果您想说 1 应该等于 1,如果它不等于 1,那么在 powershell 中使用 pester 避免代码重复的最eloquent方法是什么?

例如

{1 | should be 1} else {break}

而不是

1 | should be 1
if (1 -ne 1) {break}

目前没有用于在发生故障时中断测试执行的内置功能,但已在此处进行了讨论:https://github.com/pester/Pester/issues/360 以及一些解决方法,例如:

BeforeEach {
    $FailedCount =  InModuleScope -ModuleName Pester { $Pester.FailedCount }

    if ($FailedCount -gt 0) {
        Set-ItResult -Skipped -Because 'previous test failed'
    }
}

另一种选择可能是将您的测试分解为几个不同的 Pester 脚本。然后你可以有一些高级或初始测试,你首先检查是否成功,如果它们没有全部通过,那么你跳过剩余测试脚本的执行。

例如:

$Failed = (Invoke-Pester -Path First.tests.ps1 -PassThru).FailedCount

If ($Failed -eq 0) {
    Invoke-Pester -Path Second.tests.ps1
    ..
}