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

Conditional Mocks

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" }

Adding a When ScriptBlock

If you add a -When script block to the mock, the mock is only executed if the When block returns $true. If the When clause returns $false, PSMock will call the original method.

Mock Hello { } -When { $who -eq 'bob' }
Hello bob						# nothing
Hello jim						# "Hello, jim"

Multiple Conditional Cases

If you add more than one mock case, PSMock will look for the most recent matching case and execute that.

Mock Hello { } -When { $who -ne '' }
Mock Hello { "Hi BOB!" } -When { $who -eq 'bob' }
Hello bob						# "Hi, BOB!"
Hello jim						# nothing
Hello							# "Hello, "

A mock without a -When clause defaults to $true:

Mock Hello { } -When { $who -ne '' }
Mock Hello { "Hi, whatsyourname" }
Hello							# "Hi, whatsyourname"

If you add more than one default, the most recent default is executed.

Mock Hello { "buenos dias" }
Mock Hello { "bonjour" }
Hello							# "bonjour"

You can name a mock case with the -Name parameter. This is helpful later:

Mock Hello { "guten tag" } -Name german

When Parameters

The parameters in the When clause match the parameters of the original command. If you are creating a mock for a function or command that does not exist, then you need to specify the parameters yourself.

Mock NotAFunction { param ([string] $Path) "Return $Path" } `
	-When { param ([string] $Path) $Path -match '^c:' }
NotAFunction 'c:\foo'				# "Return c:\foo"