如何测试已解析的参数集?

时间:2015-12-19 16:57:30

标签: powershell pester

我正在尝试编写一个基本的Pester测试,用于检查已解析参数集的“高级”函数:

function Do-Stuff
{
    [CmdletBinding(DefaultParameterSetName='Set 1')]
    [OutputType([String])]

    Param
    (
        [Parameter(ParameterSetName='Set 1')] 
        [switch]
        $S1,

        [Parameter(ParameterSetName='Set 2')]
        [switch]
        $S2
    )

    $PSBoundParameters |select -ExpandProperty Keys
}

Describe Do-Stuff {
    It 'Returns "S2" when switch "S2" is set' {
        $actual = Do-Stuff -S2 
        $expexted = 'S2'
        $actual |Should Be $expexted
    }

    # How to test the resolved parameter set?
    It 'The resolved parameter set is "Set 2" when switch "S2" is set' { 
        $actual = 'What to do here?' # I'm lost ;(
        $expexted = 'Set 2'
        $actual |Should Be $expexted
    }
}

感谢名单。任何建议都会受到高度赞赏,因为我对Pester完全不熟悉。 ...在豪华和编码方面总体上要好得多:D

3 个答案:

答案 0 :(得分:2)

您可以使用the Trace-Command cmdlet

-Name参数将设置为ParameterBinderController

作为一种入门方式,请尝试这样的事情(在纠缠之外)

Trace-Command -Name ParameterBinderController -Expression { Do-Stuff -S2 } -PSHost

-PSHost选项将输出发送到主机,以便您可以看到它。

您可能不希望在Pester测试中使用它,并尝试使用其他侦听器选项和捕获输出的方法。

答案 1 :(得分:2)

以下内容将测试是否使用'设置2'对于参数S2:

Describe Do-Stuff {
    $Command = Get-Command 'Do-Stuff'

    It 'Returns "S2" when switch "S2" is set' {
        $actual = Do-Stuff -S2 
        $expexted = 'S2'
        $actual |Should Be $expexted
    }

# How to test the resolved parameter set?
    It 'The resolved parameter set is "Set 2" when switch "S2" is set' { 
        $actual = $Command.Parameters["S2"].ParameterSets.Keys
        $expexted = 'Set 2'
        $actual |Should Be $expexted
        # when you use several sets for parameters
        $expexted -contains $actual | should Be $true
   }

}

跟踪PowerShell是否实际执行'设置2',当你设置它时,不是pester测试的主题...

答案 2 :(得分:0)

使用如下:

Function Main{
  [CmdletBinding(SupportsShouldProcess=$true,DefaultParameterSetName="ViewOnly")]
Param(

[Parameter(ParameterSetName="ViewOnly")]
   [switch]$ViewOnly,

[Parameter(ParameterSetName="NukeAll")]
 [switch]$NukeAll
)

Switch ($PSCmdlet.ParameterSetName){
 "NukeAll"{
NukeAll
 }#end nuke all
"ViewOnly"{
ViewOnly
}#end viewonly
  }#end Switch

Function NukeAll {
  #Do NukeAll function code here.
 }

Function ViewOnly{
  #Do ViewOnly function code here.
 }