pesterpester-5

Format for specifying exception type in Should -Throw -ExceptionType


I'm upgrading some very old tests to work with Pester 5. Back in the day Should -Throw did not support specifying the exception type that should be thrown so I rolled my own assertion. Now I want to replace my home-made assertions with Should -Throw -ExceptionType. I can find very little online about how to specify the exception type to go with Should -Throw -ExceptionType, however.

The Pester Assertions Reference page doesn't mention -ExceptionType at all. The only reference I've found is to an old blog post, https://jakubjares.com/2017/12/19/using-should-throw/, which includes the code:

Should -Throw -ExceptionType ([ArgumentException])

Could someone please explain the format? What do the ([...]) do? And how can I specify a non-standard exception type? I want to check for a ParameterBindingValidationException. I've tried

Should -Throw -ExceptionType ([System.Management.Automation.ParameterBindingValidationException]) 

and

Should -Throw -ExceptionType ([System.Management.Automation.ParameterBindingValidationException, System.Management.Automation]) 

and

Should -Throw -ExceptionType ([System.Management.Automation.ParameterBindingValidationException, System.Management.Automation, Version=7.3.7.500, Culture=neutral, PublicKeyToken=31bf3856ad364e35]) 

but I just get an error similar to the following when I run the test:

RuntimeException: Unable to find type [System.Management.Automation.ParameterBindingValidationException]

If I replace the exception type with

Should -Throw -ExceptionType ([System.ArgumentException]) 

Pester then seems to recognise the exception type I specified. I get the following message:

Expected an exception with type [System.ArgumentException] to be thrown, but the exception type was [System.Management.Automation.ParameterBindingValidationException, System.Management.Automation, Version=7.3.7.500, Culture=neutral, PublicKeyToken=31bf3856ad364e35].

So I'm confused as to how I should specify the exception that should be thrown.


Solution

  • I was able to get it to work by using your last example, and then getting it to check for the type the error returned (which I now realise was slightly different to what you were getting):

    { get-service -blah test } | Should -Throw -ExceptionType ([System.Management.Automation.ParameterBindingException])
    

    It seems for an invalid parameter the correct type to test for is [System.Management.Automation.ParameterBindingException].

    Edit: I should add, this works for me under PowerShell 7. Might be different for you if you're using Windows PowerShell.