3

How is it possible to unmock a previously mocked function? Sometimes I find myself in a situation that I want to test a function that I previously mocked.

A simplified example:

Describe 'Pester mocking' {
    $testFile = Join-Path  $env:TEMP 'test.txt'

    It 'should be green' {
        Mock Out-File

        'Text' | Out-File -FilePath $testFile

        Assert-MockCalled Out-File -Times 1 -Exactly
    }
    It 'should be green' {
        # Unmock Out-File

        'Text' | Out-File -FilePath $testFile

        $testFile | Should -Exist
    }
}
DarkLite1
  • 13,637
  • 40
  • 117
  • 214

1 Answers1

2

Figured it out, it appears that Pester creates an alias for each mocked function. The solution would be to remove the alias from the scope. This way the real CmdLet will be called.

There are two ways of doing this depending on your version of PowerShell:

Remove-Item Alias:\Out-File
Remove-Alias Out-File

Solution:

Describe 'Pester mocking' {
    $testFile = Join-Path  $env:TEMP 'test.txt'

    It 'should be green' {
        Mock Out-File

        'Text' | Out-File -FilePath $testFile

        Assert-MockCalled Out-File -Times 1 -Exactly
    }
    It 'should be green' {
        Remove-Item Alias:\Out-File

        'Text' | Out-File -FilePath $testFile

        $testFile | Should -Exist
    }
}
DarkLite1
  • 13,637
  • 40
  • 117
  • 214