7

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.

1

3 Answers 3

7

Try this:

-parameterFilter { $Domain -eq 'MyDomain' -and $Verbose.IsPresent}
1
  • I had to use [System.Boolean]$Verbose.IsPresent -eq $true to get it work.
    – Patrick
    Nov 22, 2021 at 14:26
1

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.