抛出预期错误时,Pester 测试失败

Pester test is failing when an expected error is thrown

我正在尝试使用适用于 PowerShell 的 Pester 来测试我的一些代码,但我无法让 Pester 处理错误。

以这个非常基本的例子为例 -

using module AccessTokenRequestModel

InModuleScope -ModuleName AccessTokenRequestModel -ScriptBlock {

    ### Create a new instance of the 'AccessTokenRequest' object.
    $request = [AccessTokenRequest]::new()

    Describe -Name "the 'AccessTokenRequest' module -" -Tags @("AccessTokenRequest","Get","Unit") -Fixture {
        It "Given a valid organisation, the 'GetAccessToken' method should return a valid Access Token entity." {
            $accessTokenEntity = $request.GetAccessToken("ValidOrg")
            $accessTokenEntity.PartitionKey | Should be "AccessToken"
            $accessTokenEntity.RowKey | Should be "ValidOrg"
            $accessTokenEntity.AccessToken | Should be "12345"
        }

        It "Given an invalid organisation, the 'GetAccessToken' method should throw an error of type 'AccessTokenNotFoundException.'" {
            $request.GetAccessToken("FakeOrg") | Should -Throw
        }
    }
}

调用 $tokens.GetAccessToken("FakeOrg") 导致抛出 AccessTokenNotFoundException 类型的错误,但是 Pester 测试失败。

Describing the 'AccessTokenRequest' module -
  [+] Given a valid organisation, the 'GetAccessToken' method should return a valid Access Token entity. 70ms
  [-] Given an invalid organisation, the 'GetAccessToken' method should throw an error of type 'AccessTokenNotFoundException.' 61ms
    AccessTokenNotFoundException: Access Token for organisation 'NonExistentAccessTokenTest' does not exist.
    at GetAccessTokenEntity, C:\Users\dgard\OneDrive - Landmark Information Group Ltd\Function Apps\AzureDevOpsVariableChecker\Modules\AccessTokenService\AccessTokenService.psm1: line 73
    at GetAccessToken, C:\Users\dgard\OneDrive - Landmark Information Group Ltd\Function Apps\AzureDevOpsVariableChecker\Modules\AccessTokenRequestModel\AccessTokenRequestModel.psm1: line 25
    at <ScriptBlock>, C:\Users\dgard\OneDrive - Landmark Information Group Ltd\Function Apps\AzureDevOpsVariableChecker\Tests\Unit\AccessTokenRequest.Tests.ps1: line 42

错误是由 throw 命令生成的,因此是终止错误,如 . And unless I'm misinterpreting the documentation 中所建议的那样,它表明 should -throw 评估的抛出错误应该通过.

我在这里遗漏了什么 - 抛出错误时如何使此测试通过?

当测试 -Throw 时,Should 的输入需要是 scriptblock(所以用大括号括起来),所以将测试更改为:

{ $request.GetAccessToken("FakeOrg") } | Should -Throw