我如何通过 Powershell Pester 测试 ThrowTerminatingError

How do I Powershell Pester Test for ThrowTerminatingError

我如何通过 Powershell Pester 测试 ThrowTerminatingError?

catch
{
    $PSCmdlet.ThrowTerminatingError( $PSItem )
}

输出:

Missed command:

File                  Class Function          Line Command
----                  ----- --------          ---- -------
Test-ServerOnline.ps1       Test-ServerOnline   50 $PSCmdlet.ThrowTerminatingError( $PSItem )

为了 在 Pester 测试中捕获 终止 错误(异常):

  • 您必须 将输入命令包含在 脚本块中 ({ ... })

  • 并测试
    Should -Throw / Should -Not -Throw[ 是否发生/未发生此类错误=39=]

注意:如果您也想用这种方式处理非终止错误Should -Throw 句柄:

  • 如果输入命令调用cmdlet/高级函数,向其添加公共参数-ErrorAction Stop,这会将(第一个)非终止错误提升为(脚本)终止(致命的)一个。

  • 否则,将$ErrorActionPreference = 'Stop'设置为脚本块内的第一个语句


例子:

注意:为简洁起见,以下片段不是完整的 Pester 测试,仅调用 Pester Should cmdlet;但是,您 可以 按原样调用它们,在这种情况下 成功测试 表示接收 没有输出 .有关完整示例,请参阅底部部分。

# Note the { ... } around the command.
{ 1 / 0 } | Should -Throw

上面的测试通过了,因为 1 / 0 创建了一个语句终止错误,这与 $PSCmdlet.ThrowTerminatingError() 产生的错误类型相同。

出现非终止错误升级为终止错误-ErrorAction Stop

# Note: Without -ErrorAction Stop, the test would fail, because
#       not finding a file is a non-terminating error.
{ Get-Item NoSuchFile -ErrorAction Stop } | Should -Throw

此外,您可以测试特定的错误 ID,使用 -ErrorId参数:

{ 1 / 0 } | Should -Throw -ErrorId RuntimeException

上面的测试通过了,因为1 / 0触发的语句终止错误产生的错误记录(也记录在自动$Error变量中),有一个.FullyQualifiedErrorId RuntimeException 的值(之后用 $Error[0].FullyQualifiedErrorId 验证)。

注意:-ErrorId执行字面子字符串匹配,这样-ErrorId Runtime在命令中也可以工作以上。

或者,您可以测试特定的异常类型,使用-ExceptionType参数:

{ 1 / 0 } | Should -Throw -ExceptionType System.Management.Automation.RuntimeException

请注意,您必须传递完整类型名称;省略 System. 组件(PowerShell 通常允许)是 not-ExceptionType.

识别

要识别与最近错误相关的异常类型,请使用 $Error[0].Exception.GetType().FullName


完整示例:

将以下内容存储在 *.tests.ps1 文件中并直接或通过 Invoke-Pester.
调用它 所有这些测试都应该通过。

Describe "Error-handling tests" {

  BeforeAll {
    # Define an advanced function that generates a terminating error.
    function Get-FooTerminating {
      [CmdletBinding()]
      param()
      # When invoked by Pester, $PSCmdlet.ThrowTerminatingError()
      # would have the same effect here, but note that $PSCmdlet.ThrowTerminatingError()
      # creates a *statement*-terminating error, whereas Throw creates a more
      # severe *script*-terminating (thread-terminating) error.
      Throw "me for a loop"
    }
    
    # Define an advanced function that generates a non-terminating error.
    function Get-FooNonTerminating {
      [CmdletBinding()]
      param()
      Write-Error "Something went mildly wrong."
    }

  }

  It "A terminating error throws." {
    { Get-FooTerminating } | Should -Throw
  }

  It "A non-terminating error doesn't throw." {
    # Note: Non-terminating errors are *passed through*, so
    #       we silence them with 2>$null here.
    { Get-FooNonTerminating 2>$null } | Should -Not -Throw
  }

  It "A non-terminating error promoted to a terminating one does throw." {
    { Get-FooNonTerminating -ErrorAction Stop } | Should -Throw
  }

  It "A fully qualified error ID can be tested for." {
    # Test for a (substring of) the error record's .FullyQualifiedErrorId 
    { NoSuchCommand } | Should -Throw -ErrorId CommandNotFound
  }

  It "A specific exception type can be tested for." {
    # Note the need to specify the type name *in full*, including the
    # 'System.' part
    { NoSuchCommand } | Should -Throw -ExceptionType System.Management.Automation.CommandNotFoundException
  }


}

根据 mklement0 的回答,您需要将通过管道传输到脚本块中的断言的任何内容包装起来,以便使用 -Throw 检查。这是您需要执行此操作的唯一断言类型。

请注意,您也可以使用 -Not:

来取消检查
Describe 'Test' { 
    It 'Should Throw' { 
        { Throw } | Should -Not -Throw 
    }
}

Returns:

Describing Test
  [-] Should Throw 15ms
    Expected no exception to be thrown, but an exception "ScriptHalted" was thrown from line:3 char:11
        +         { Throw } | Should -Not -Throw
        +           ~~~~~.
    3:         { Throw } | Should -Not -Throw