'Pester Mocking CmdLets

I have question regarding to the mocking mechanism in Pester. I have a script Script.ps1 that I want to test. The tests are located in Script.Tests.ps1. In Script.ps1 I implemented the following function:

function Start-Executable {
    param([string]$Executable)

    Start-Process $Executable
}

For testing purpose I want to mock Start-Process. The Script.Tests.ps1 contains the following test.

BeforeAll{
   . $PSScriptRoot/Script.ps1
}

Describe 'Start-Executable' {
    Mock -CommandName 'Start-Process' -MockWith {return $null}
    
    It 'Start-Process is called.'{

       Start-Executable -Executable 'Test.exe'
       Assert-MockCalled 'Start-Process'
    }
}

If I execute the test, the real Start-Process throws an exception that 'Test.exe' could not be found. If I move the mock in the It-block, the test passes. I would like to add the mock in the Describe-block (or later, as more tests are getting written, in the Context-block) to have one mock covering a bench of tests. Is this possible and what I am doing wrong?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source