I want to write a test in PowerShell with Pester 5.4.0 to check whether a specific exception type has been thrown inside a script block. It should be fairly easy, but I am somehow not doing it right. Following along the Pester v5 documentation for the Should keyword and this pre-release Pester blogpost about using Should - Throw I wrote the following (very basic) script containing one test:
Import-Module Pester -RequiredVersion 5.4.0
Describe "Testing if a service is registed." {
It "This service should not be registered in the windows services app." {
{ Get-Service -Name "this service does not exist" } | Should -Throw -ExceptionType ([Microsoft.PowerShell.Commands.ServiceCommandException])
}
}
I would expect the test to catch the ServiceCommandException that is thrown when the Get-Service Cmdlet looks for a service that does not exist, and the test to pass. Instead the error is still thrown, Pester tells me that Expected an exception, with type [Microsoft.PowerShell.Commands.ServiceCommandException] to be thrown, but no exception was thrown., and the test fails:
I am probably doing something that's very obvious wrong here, but I looked at it for a while and did some research, and I cannot see what is wrong with my script.