简体   繁体   English

如何使用 Pester 测试函数(如何循环 Context 块)

[英]How to test functions using Pester (how to loop Context block)

Hi i am trying to test my functions in the module but I need to know the right syntax.嗨,我正在尝试在模块中测试我的功能,但我需要知道正确的语法。 Here is what i have so far.这是我到目前为止所拥有的。

#array of functions 
     
$functions=('Get-Values',
            'Set-Value',
            'Publish-Value')

foreach($function in $functions) 
  
Context "Test Function $functions"{
    It "$function should exist"{
        "$function" | Should Exist 
    }
}

First this is invalid PowerShell syntax.首先,这是无效的 PowerShell 语法。 The foreach loop body must always be enclosed in curly braces: foreach($function in $functions) { <# loop body #> } . foreach循环体必须始终用花括号括起来: foreach($function in $functions) { <# loop body #> }

Apart from that, Pester doesn't support regular loops around the structural elements like Describe , Context and It .除此之外,Pester 不支持围绕结构元素(如DescribeContextIt )的常规循环。 Since Pester 5 you can use data driven tests instead:Pester 5 开始,您可以改用数据驱动测试

Describe 'My Functions' {

    Context 'Test Function <name>' -ForEach @(
        @{ Name = 'Get-Values' }
        @{ Name = 'Set-Value' }
        @{ Name = 'Publish-Value' }
    ) {
        It 'should exist'  {
            Get-Command $name -EA SilentlyContinue | Should -Not -BeNullOrEmpty
        }
    }
}

Also, Should -Exist tests for existence of filesystem items only.此外, Should -Exist测试文件系统项的存在。 To test existence of command, use Get-Command .要测试命令是否存在,请使用Get-Command The parameter -EA ( -ErrorAction ) SilentlyContinue suppresses error output from Get-Command , when command isn't found.当找不到命令时,参数-EA ( -ErrorAction ) SilentlyContinue会抑制Get-Command错误输出。 In this case Get-Command outputs $null , so with | Should -Not -BeNullOrEmpty在这种情况下, Get-Command输出$null ,所以使用| Should -Not -BeNullOrEmpty | Should -Not -BeNullOrEmpty we check if command exists. | Should -Not -BeNullOrEmpty我们检查命令是否存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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