有没有一种方法可以使用Pester测试/声明Write-Host的输出?

时间:2020-03-03 15:44:34

标签: powershell pester

我正在为一个相当复杂的脚本编写测试,并且脚本中有一个特定的功能,它将向用户输出不同系列的日志消息。我想断言是否正在显示特定的日志记录消息。

主要问题是我不知道哪个参数隐式处理了我正在传递Write-Host cmdlet的文本。

这里有一些代码捕捉了我要做的事情的前提...

测试功能

function TestFunction($TestInput) {
    if ($TestInput -contains 1) {
        Write-Host "TestInput contains a 1"
    }

    if ($TestInput -contains 3 ) {
        Write-Host "TestInput contains a 3"
    }

    if ($TestInput -contains 4 ) {
        Write-Host "TestInput contains a 4"
    }
}

Pester测试

Describe "TestFunction" {
    It "should call Write-Host with appropriate message if 1 or 3 is passed" {
        Mock Write-Host {}
        TestFunction -TestInput @(1, 2, 3)
        Assert-MockCalled Write-Host -Exactly 2 -Scope It
        Assert-MockCalled Write-Host -Exactly 1 -Scope It -ParameterFilter { "TestInput contains a 1" }
        Assert-MockCalled Write-Host -Exactly 1 -Scope It -ParameterFilter { "TestInput contains a 3" }
    }
}

输出

  Describing TestFunction
    [-] should call Write-Host with appropriate message if 1 or 3 is passed 19ms
      at <ScriptBlock>, : line 235
      235:         Assert-MockCalled Write-Host -Exactly 1 -Scope It -ParameterFilter { "TestInput contains a 1" }
      Expected Write-Host to be called 1 times exactly but was called 2 times
Tests completed in 106ms
Tests Passed: 0, Failed: 1, Skipped: 0, Pending: 0, Inconclusive: 0 

1 个答案:

答案 0 :(得分:7)

查看Microsoft documentation for the Write-Host cmdlet之后,我发现有一个-Object参数。这将接受一组通用对象以写入控制台。 -Object参数是Pester测试的-ParameterFilter中需要指定的参数,以断言正在显示适当的文本。

我更新的代码如下...

测试功能

function TestFunction($TestInput) {
    if ($TestInput -contains 1) {
        Write-Host "TestInput contains a 1"
    }

    if ($TestInput -contains 3 ) {
        Write-Host "TestInput contains a 3"
    }

    if ($TestInput -contains 4 ) {
        Write-Host "TestInput contains a 4"
    }
}

Pester测试

Describe "TestFunction" {
    It "should call Write-Host with appropriate message if 1 or 3 is passed" {
        Mock Write-Host {}
        TestFunction -TestInput @(1, 2, 3)
        Assert-MockCalled Write-Host -Exactly 2 -Scope It
        Assert-MockCalled Write-Host -Exactly 1 -Scope It -ParameterFilter { $Object -eq "TestInput contains a 1" }
        Assert-MockCalled Write-Host -Exactly 1 -Scope It -ParameterFilter { $Object -eq "TestInput contains a 3" }
    }
}

输出

  Describing TestFunction
    [+] should call Write-Host with appropriate message if 1 or 3 is passed 20ms
Tests completed in 99ms
Tests Passed: 1, Failed: 0, Skipped: 0, Pending: 0, Inconclusive: 0