Search code examples
powershellunit-testingpester

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

Solution

  • 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