Powershell 单元测试用例

Powershell Unit test cases

我在 powershell 中有一个命令,我调用同一个命令两次,我期待第一次它会 return 一个值,第二次它会抛出一个错误,知道如何测试这个块代码? 如何为我的模拟命令提供多个实现?

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

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

你可以这样做:

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
}

您可以向 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,但这可以通过点采购脚本在这一点上轻松完成