Can Pester mock an exception? Can Pester mock an exception? powershell powershell

Can Pester mock an exception?


Yes it can! Here's an example:

Describe 'Mock an exception' {    Mock Get-WMIObject { Throw 'some error' }    It 'Get-WMIObject should throw' {        {Get-WMIObject -class someclass} | Should Throw 'some error'    }}

I think your code isn't working because:

{ Test-Is64Bit } | Should Be $false

Should be:

 { Test-Is64Bit } | Should Throw

You use a ScriptBlock { } before a Should when you're using Should Throw.


function Test-LocalFile{    param (        [string]        $filepath    )    try {        $FileInfo = get-item -Path $filepath -ErrorAction SilentlyContinue        if ($FileInfo.getType().Name -eq "FileInfo") {            return $true        }    } catch {         Write-Error -Message "$($_.Exception.Message)"         Throw    }}

Here is the total solution for the upper defined function how to handle the exception

Describe "Unit testing for exception handling" {    Context "unit test showing exception"{    #arrange    Mock Write-Error{}    Mock get-item  {           Throw 'some error'    }    #act    Write-Error 'some error'    #assert    It "test-Local FileThrows exception" {             {Test-LocalFile -filepath test.txt}  | Should Throw 'some error'            Assert-MockCalled get-item -Scope It -Exactly -Times 1        }    }}