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.
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.
Mocks the behavior of an existing command with an alternate implementation.
Checks if any Verifiable Mock has not been invoked. If so, this will throw an exception.
Checks if a Mocked command has been called a certain number of times and throws an exception if it has not.
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: