'Pester test is failing when an expected error is thrown

I'm trying to use Pester for PowerShell to test some of my code, but I'm unable to get Pester to work in relation to errors.

Take this very basic example -

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
        }
    }
}

The call to $tokens.GetAccessToken("FakeOrg") resutls in an error of type AccessTokenNotFoundException being thrown, however the Pester test is failing.

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

The error is being generated by a throw command and so is a terminating error, as suggested in this question. And unless I'm misinterpreting the documentation, it suggests that a thrown error being evaluated by should -throw should pass.

What am I missing here - how can I make this test pass when an error is thrown?



Solution 1:[1]

When testing for a -Throw the input to Should needs to be a scriptblock (so encased in curly braces), so change your test to this:

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mark Wragg