Mocking with Pester
Pester provides a set of Mocking functions making it easy to fake dependencies and also to verify behavior. Using these mocking functions can allow you to "shim" a data layer or mock other complex functions that already have their own tests.
Description
With the set of Mocking functions that Pester exposes, one can:
- Mock the behavior of ANY powershell command.
- Verify that specific commands were (or were not) called.
- Verify the number of times a command was called with a set of specified parameters.
Mocking Functions
Mock
Mocks the behavior of an existing command with an alternate implementation.
Assert-VerifiableMocks
Checks if any Verifiable Mock has not been invoked. If so, this will throw an exception.
Assert-MockCalled
Checks if a Mocked command has been called a certain number of times and throws an exception if it has not.
Example
If you need to mock calls to commands which are made from inside a Script Module, additional code is required. For details, refer to Unit Testing within Modules
Mocking a function that is called by a method in a PowerShell class
In PowerShell 6, functions called by classes can be mocked as above, with no known problems.
However previous versions of PowerShell, including all versions of Windows PowerShell up to 5.1 cache class definitions in such a way that they are never redefined, even if you remove the module and re-import, or modify the class. This breaks Pester's Mock command, as the scope where the mock must be injected cannot be found.
Dave Wyatt has provided this workaround:
Simply run your Pester tests in a fresh session every time; this is simple to do with Start-Job. I have this proxy function in my PowerShell profile to help with that: