簡體   English   中英

有沒有辦法使用 Pester 測試/斷言來自 Write-Host 的輸出?

[英]Is there a way to test / assert output from Write-Host using 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"
    }
}

糾纏測試

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 

在查看了Write-Host cmdlet 的Microsoft 文檔后,我發現有一個-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"
    }
}

糾纏測試

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 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM