Reputation: 618
Using Pester, I'm mocking an advanced function which takes, amongst other parameters, a switch. How do I create a -parameterFilter
for the mock which includes the switch parameter?
I've tried:
-parameterFilter { $Domain -eq 'MyDomain' -and $Verbose -eq $true }
-parameterFilter { $Domain -eq 'MyDomain' -and $Verbose }
-parameterFilter { $Domain -eq 'MyDomain' -and $Verbose -eq 'True' }
to no avail.
Upvotes: 7
Views: 5488
Reputation: 1568
-Verbose
is a common parameter, which makes this a bit more tricky. You never actually see a $Verbose
variable in your function, and the same applies to the parameter filter. Instead, when someone sets the common -Verbose
switch, what actually happens is the $VerbosePreference
variable gets set to Continue
instead of SilentlyContinue
.
You can, however, find the Verbose switch in the $PSBoundParameters
automatic variable, and you should be able to use that in your mock filter:
Mock someFunction -parameterFilter { $Domain -eq 'MyDomain' -and $PSBoundParameters['Verbose'] -eq $true }
Upvotes: 1
Reputation: 81
Try this:
-parameterFilter { $Domain -eq 'MyDomain' -and $Verbose.IsPresent}
Upvotes: 8
Reputation: 747
The following appears to work fine:
Test.ps1 - This just contains two functions. Both take the same parameters but Test-Call
calls through to Mocked-Call
. We will mock Mocked-Call
in our tests.
Function Test-Call {
param(
$text,
[switch]$switch
)
Mocked-Call $text -switch:$switch
}
Function Mocked-Call {
param(
$text,
[switch]$switch
)
$text
}
Test.Tests.ps1 - This is our actual test script. Note we have two mock implementations for Mocked-Call
. The first will match when the switch
parameter is set to true. The second will match when the text
parameter has a value of fourth and the switch
parameter has a value of false.
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path).Replace(".Tests.", ".")
. "$here\$sut"
Describe "Test-Call" {
It "mocks switch parms" {
Mock Mocked-Call { "mocked" } -parameterFilter { $switch -eq $true }
Mock Mocked-Call { "mocked again" } -parameterFilter { $text -eq "fourth" -and $switch -eq $false }
$first = Test-Call "first"
$first | Should Be "first"
$second = Test-Call "second" -switch
$second | Should Be "mocked"
$third = Test-Call "third" -switch:$true
$third | Should Be "mocked"
$fourth = Test-Call "fourth" -switch:$false
$fourth | Should Be "mocked again"
}
}
Running the tests shows green:
Describing Test-Call
[+] mocks switch parms 17ms
Tests completed in 17ms
Passed: 1 Failed: 0
Upvotes: 0