Throw is used to test whether or not a block of code throws a terminating error. Throw has a number of different usage scenarios. The simplest is detecting whether a terminating error (of any kind) is thrown:
function Invoke-Something { throw } Describe Invoke-Something { It 'Throws a terminating error' { { Invoke-Something } | Should Throw } }
When testing for terminating errors, the subject of the test is placed in a script block (curly braces).
Pester allows testing of the error message:
function Invoke-Something { throw 'an error' } Describe Invoke-Something { It 'Throws a terminating error' { { Invoke-Something } | Should Throw 'an error' } }
Pester also allows testing of the fully qualified error ID:
function Invoke-Something { $errorRecord = New-Object System.Management.Automation.ErrorRecord( (New-Object Exception('an error')), 'AnErrorID', 'OperationStopped', $null ) throw $errorRecord } Describe Invoke-Something { It 'Throws a terminating error' { { Invoke-Something } | Should -Throw -ErrorId 'AnErrorId' } }
If a function is written such that it writes a non-terminating error (using Write-Error), and generation of that error must be tested, the following pattern might be used:
function Invoke-Something { [CmdletBinding()] param ( )
Write-Error 'Error' } Describe Invoke-Something { It 'Throws a non-terminating error' { { Invoke-Something -ErrorAction SilentlyContinue }| Should -Not -Throw { Invoke-Something -ErrorAction Stop } | Should -Throw } }