我正在尝试使用Pester for PowerShell来测试我的一些代码,但无法使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命令生成的,因此终止错误也是如此,如this question中所建议。除非我误解了documentation,否则它表明应该通过should -throw评估抛出的错误。

我在这里缺少什么-引发错误时如何使该测试通过?

最佳答案

在测试-Throw时,向Should的输入必须是scriptblock(因此用花括号括起来),因此将测试更改为:

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

10-06 14:07