Usually, a mock to produce an error, with a test to verify you got the error looks like this:
Test code
Describe 'mock an error' {
Context 'terminating error' {
Mock -CommandName Set-Location -MockWith {Write-Error 'My Error' -ErrorAction 'Stop'}
it 'should throw' {
{Set-Location -Path .\foo -ErrorAction Stop} | should throw 'My Error'
}
}
Context 'non-terminating error' {
Mock -CommandName Set-Location -MockWith {Write-Error 'My Error' }
it 'should throw' {
{Set-Location -Path .\foo -ErrorVariable slError
$Global:slError=$slError} | should not throw
$global:slError.count |should be 1
$Global:slError[0].Exception.Message | should be 'My Error'
}
}
}
Results
Describing mock an error
Context terminating error
[+] should throw 551ms
Context non-terminating error
Write-Error 'My Error' : My Error
At C:\Program Files\WindowsPowerShell\Modules\Pester\3.4.0\Functions\Mock.ps1:1056 char:9
+ & $___ScriptBlock___ @___BoundParameters___ @___ArgumentList_ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException
[+] should throw 164ms