簡體   English   中英

Powershell 單元測試用例

[英]Powershell Unit test cases

我在 powershell 中有一個命令,我兩次調用相同的命令,我期待它第一次返回一個值,第二次它會拋出一個錯誤,知道如何測試這個代碼塊嗎? 如何為我的模擬命令提供多種實現?

try{
      Write-output "hello world"
}Catch{
throw "failed to print"
}

try {
     write-output "hello world"
}Catch{
throw "failed to print hello world"
} 

您可以向 Mock 添加一些邏輯,以便它檢查之前是否已執行過,然后結果會有所不同。

下面的 Pester 檢查腳本是否拋出了我們預期的確切錯誤消息,並檢查Write-Output被調用了兩次:

Function YourCode {

    try{
          Write-output "hello world"
    }
    catch{
        throw "failed to print"
    }

    try {
         write-output "hello world"
    }
    catch{
        throw "failed to print hello world"
    }
} 


Describe 'YourCode Tests' {

    $Script:MockExecuted = $false

    Mock Write-Output {

        if ($Script:MockExecuted) {
            Throw
        }
        else {
            $Script:MockExecuted = $true
        }
    }

    It 'Should throw "failed to print hello world"' {
        { YourCode } | Should -Throw 'failed to print hello world'
    }

    It 'Should have called write-output 2 times' {
        Assert-MockCalled Write-Output -Times 2 -Exactly
    }
}

請注意,我將您的代碼包裝在一個函數中,以便可以在腳本塊內調用它來檢查Throw ,但這可以通過此時點源腳本來輕松完成

你可以這樣做:

try
{
  First statement 
}
catch 
{
  The Statement When Error
}
try 
{
  Second statement 
}
catch
{
  The statement when error
}

作為 Wasif 答案的補充,請確保 try 塊內的任何 cmdlet 都應包含 ErrorAction 標志,以便在失敗時將其傳遞給 catch 塊。

try {
    Get-Process abc -ErrorAction STOP
}
catch {
    # Error Message
}

暫無
暫無

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

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