Skip to content
Jon Wagner edited this page Feb 8, 2013 · 1 revision

Call Tracking

PSMock keeps track of all of the calls to mocks. In test scenarios, this lets you verify that certain mocks were called.

First, make sure you have imported the PSMock module and enabled mocking in your script:

Import-Module PSMock
Enable-Mock | iex
function Hello { param ([string] $who) "Hello, $who" }

Mock Statistics

When you create a mock, you can specify the -OutputMock switch to get a handle to the mock.

$mock = Mock Hello { "Hi" } -OutputMock

You can also get the mock from Get-Mock:

$mock = Get-Mock Hello

The mock contains a few tracking values:

  • Count - the number of times the mock was called.
  • Calls - an array of each call. Each entry contains:
    • CommandName - the name of the command
    • BoundParameters - a hashtable of bound parameters
    • Args - any unbound arguments

Verifying that Mocks are Called

You can use this to verify that mocks are being called properly in your tests:

$mock = Mock Hello { "Hi" } -OutputMock
Hello bob				# "Hi"
Hello jim				# "Hi"

$mock.Count				# 2
$mock.Calls[0].BoundParameters['who']	# bob

Case-Level Statistics

If you create multiple cases for your mock, the calls are tracked separately:

$bob = Mock Hello { "Hi" } -When { $who -eq 'bob' } -Name bob -OutputCase
$jim = Mock Hello { "Hi" } -When { $who -eq 'jim' } -Name jim -OutputCase

You can also get these values from Get-Mock:

$bob = Get-Mock Hello -Case bob
$jim = Get-Mock Hello -Case jim

Or from the mock itself:

$mock = Get-Mock Hello
$bob = $mock.Cases['bob']
$bob = $mock.Cases['jim']

The case-level objects have the same tracking values as the mock does.

Call Tracking in a Mock Context

Because PSMock separates mock contexts, if you override a mock in a nested context, the calls to the nested context mock are not recorded against the outer context mock.