简体   繁体   中英

Powershell Unit test cases

I have a command in powershell and I am calling same command two times and I am expecting first time it will return a value and second time it will throw a error , any idea how to test this block of code? how can I provide multiple implementation for my mock command?

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

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

You could add some logic to the Mock so that it checks whether it had been executed previously and then behaves differently as a result.

The below Pester checks that the script threw the exact error message we expected, and also checks that Write-Output was invoked twice:

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
    }
}

Note I wrapped your code in a function so that it could be called inside a scriptblock to check for the Throw , but this could just as easily be done by dot sourcing a script at this point

You can do this:

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

As an addendum to Wasif's answer, please make sure that any cmdlet inside the try block, should contain the ErrorAction flag to pass it to the catch block when it fails.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM