2

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"
} 
IronManUTF8
  • 57
  • 1
  • 5

3 Answers3

1

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

Mark Wragg
  • 22,105
  • 7
  • 39
  • 68
0

You can do this:

try
{
  First statement 
}
catch 
{
  The Statement When Error
}
try 
{
  Second statement 
}
catch
{
  The statement when error
}
Wasif
  • 14,755
  • 3
  • 14
  • 34
  • 2
    Hi, I want to test that block of code with pester. how can I provide multiple implementation for my mock command? – IronManUTF8 Dec 19 '19 at 08:46
0

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
}
Vish
  • 466
  • 2
  • 12