首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >有没有办法使用Pester测试/断言Write-Host的输出?

有没有办法使用Pester测试/断言Write-Host的输出?
EN

Stack Overflow用户
提问于 2020-03-03 23:44:35
回答 1查看 1.7K关注 0票数 4

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

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

下面是一些代码,它们抓住了我想要做的事情的前提……

要测试的函数

代码语言:javascript
复制
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"
    }
}

纠缠测试

代码语言:javascript
复制
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" }
    }
}

输出

代码语言:javascript
复制
  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 
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-03-03 23:44:35

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

我的更新代码如下...

要测试的函数

代码语言:javascript
复制
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"
    }
}

纠缠测试

代码语言:javascript
复制
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" }
    }
}

输出

代码语言:javascript
复制
  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 
票数 10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60510816

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档