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
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:
Mocks are no longer effective in the whole
Context in which they were placed. Instead they will default to the block in which they were placed. Both of these work:
Counting mocks depends on where the assertion is placed. In
AfterEach it defaults to
It scope. In
AfterAll, it default to
Context based on the command that contains them. The default can still be overriden by specifying
Mock counting assertions were renamed to
Should -Invoke and
Should -InvokeVerifiable, and most of their parameters are no longer positional.
Assert-VerifiableMock are provided as functions, and are deprecated.
Parameter filters no longer require you to use