-
Notifications
You must be signed in to change notification settings - Fork 3
A Quick Tour
Assuming you have already downloaded the PSMock module, start off by importing it.
Import-Module PSMock
The next thing you need to do is to enable mocks for your current script. This is done with the Enable-Mock call. Enable-Mock defines the Mock
function in your script, so PSMock has a chance to inspect functions in your script's scope. You need to do this once per script.
Enable-Mock | iex
So let's say you have an original function:
function Original { "original" }
Original # "original"
You can mock it with the Mock command. In this case, we will override all calls to Original:
Mock Original { "mocked" }
Original # "mocked"
We can also remove the mock:
Remove-Mock Original
Original # "original"
Sometimes you want different code to execute depending on the parameters. You can use the When parameter to filter the execution:
function Hello { param ([string] $who) "Hello, $who" }
Hello you # "Hello, you"
Mock Hello { } -when { $who -eq "Bob" }
Hello you # "Hello, you"
Hello bob # nothing
Mock Hello { "Good day, $who" }
Hello bob # nothing
Hello you # "Good day, you"
Remove-Mock Hello
Hello bob # "Hello, bob"
Hello you # "Hello, you"
If you are using mocks for testing, you may want to look at the statistics that PSMock keeps for the mocks:
Mock Hello { } -when { $who -eq "Bob" } -name Bob
Mock Hello { "Good day, $who" }
Hello bob # nothing
Hello you # "Good day, you"
(Get-Mock Hello).Count # 2
(Get-Mock Hello -case Bob).Count # 1
(Get-Mock Hello -case default).Count # 1
(Get-Mock Hello -case default).Calls[0].BoundParameters['who'] # "you"
You can also use MockContexts to automatically remove certain sets of mocks. This is very handy for more complicated test scenarios. You can even nest MockContexts.
MockContext {
Mock Hello { } -when { $who -eq "Bob" } -name Bob
Hello bob # nothing
}
Hello bob # "Hello, bob"