如何在Pester中模拟时使用参数过滤器和开关参数?

7

我使用 Pester 进行模拟,它需要模拟一个高级函数,该函数包含了一些参数,其中还有一个开关。如何为 Mock 创建一个 -parameterFilter 并包含该开关参数?

我尝试过以下代码:

-parameterFilter { $Domain -eq 'MyDomain' -and $Verbose -eq $true }

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

-parameterFilter { $Domain -eq 'MyDomain' -and $Verbose -eq 'True' }

无济于事。

你是否收到了实际的错误信息?当被测试的主题已经作为模块导入时,模拟调用存在问题。请注意这里讨论的限制 https://github.com/pester/Pester/wiki/Mocking-with-Pester - Kieranties
3个回答

7

试试这个:

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

我不得不使用[System.Boolean]$Verbose.IsPresent -eq $true才能让它工作。 - Patrick

1

-Verbose是一个常见的参数,这使得它有点棘手。在您的函数中,您实际上从未看到过$Verbose变量,参数筛选器也是如此。相反,当有人设置常见的-Verbose开关时,实际发生的是$VerbosePreference变量被设置为Continue而不是SilentlyContinue

但是,您可以在$PSBoundParameters自动变量中找到Verbose开关,并且应该能够在模拟筛选器中使用它:

Mock someFunction -parameterFilter { $Domain -eq 'MyDomain' -and $PSBoundParameters['Verbose'] -eq $true }

0

以下看起来工作正常:

Test.ps1 - 它只包含两个函数。两个函数都需要相同的参数,但是 Test-Call 会调用 Mocked-Call。我们将在测试中模拟 Mocked-Call

Function Test-Call {
    param(
        $text,
        [switch]$switch
    )

    Mocked-Call $text -switch:$switch
}

Function Mocked-Call {
    param(
        $text,
        [switch]$switch
    )

    $text
}

Test.Tests.ps1 - 这是我们实际的测试脚本。请注意,我们有两个Mocked-Call的模拟实现。第一个将匹配当switch参数设置为true时。第二个将匹配当text参数的值为fourth并且switch参数的值为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"

    }
}

运行测试显示为绿色。
Describing Test-Call
[+]   mocks switch parms 17ms
Tests completed in 17ms
Passed: 1 Failed: 0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接