简体   繁体   中英

How can I user a parameterFilter with a switch parameter when mocking in Pester?

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.

尝试这个:

-parameterFilter { $Domain -eq 'MyDomain' -and $Verbose.IsPresent}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM