【问题标题】:How can I user a parameterFilter with a switch parameter when mocking in Pester?在 Pester 中进行模拟时,如何使用带有 switch 参数的 parameterFilter?
【发布时间】:2013-11-11 19:03:59
【问题描述】:

使用 Pester,我正在模拟一个高级函数,该函数除其他参数外还包含一个开关。如何为包含 switch 参数的模拟创建-parameterFilter

我试过了:

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

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

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

无济于事。

【问题讨论】:

标签: powershell pester


【解决方案1】:

试试这个:

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

【讨论】:

  • 我必须使用 [System.Boolean]$Verbose.IsPresent -eq $true 才能让它工作。
【解决方案2】:

-Verbose 是一个常见的参数,这使得这有点棘手。您实际上从未在函数中看到 $Verbose 变量,这同样适用于参数过滤器。相反,当有人设置常见的-Verbose 开关时,实际发生的情况是$VerbosePreference 变量被设置为Continue 而不是SilentlyContinue

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

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

【讨论】:

    【解决方案3】:

    以下似乎工作正常:

    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 时,第二个将匹配。 p>

    $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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多