繁体   English   中英

我如何 Powershell 纠缠测试 ThrowTerminatingError

[英]How do I Powershell Pester Test for ThrowTerminatingError

如何 Powershell Pester 测试 ThrowTerminatingError?

catch
{
    $PSCmdlet.ThrowTerminatingError( $PSItem )
}

Output:

Missed command:

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

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

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

  • 并测试这样的错误是否发生/没有发生
    Should -Throw / Should -Not -Throw

注意:如果您还想以这种方式处理非终止错误Should -Throw不会处理:

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

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


例子

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

# 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

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

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

上述测试通过,因为由1 / 0触发的语句终止错误产生的错误记录(也记录在自动$Error变量中)具有RuntimeException.FullyQualifiedErrorId值(使用$Error[0].FullyQualifiedErrorId然后)。

注意: -ErrorId执行文字substring 匹配,因此-ErrorId Runtime也可以在上面的命令中工作。

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

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

请注意,您必须传递完整的类型名称 省略System. -ExceptionType无法识别组件( -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 的回答,您需要将 pipe 包装到脚本块中的断言中,以便使用-Throw检查。 这是您需要执行此操作的唯一断言类型。

请注意,您还可以使用-Not否定检查:

Describe 'Test' { 
    It 'Should Throw' { 
        { Throw } | Should -Not -Throw 
    }
}

回报:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM