Search code examples
powershellpowershell-5.0pester

Can I use If/Else statement in Pester?


I want to test a function when it succeeds but also whether it throws the correct error when it fails.

I wrote a function Test-URLconnection which should test whether a URL is accessible, otherwise it should throw an error.

Describe 'Test-URLconnection'{
    $Error.Clear()
    $countCases = @(
        @{'url' = 'www.google.com'}
        @{'url' = 'www.facebook.com'}
        @{'url' = 'www.bbc.com'}
    )

    It "The URL status should be confirmed." -TestCases $countCases {
        param($url)

        if ([bool](test-URLconnection -URL $url -ErrorAction SilentlyContinue)) {
            test-URLconnection -URL $url | Should -Be "$url = OK"    
        }
        else {
            $Error[0].Exception.Message | Should -Be "$url cannot be accessed."
        }
    }
}

I expected the two tests to pass because, even though Facebook cannot be accessed via Invoke-WebRequest (the command which I use in Test-URLconnection) it should have been caught with the else-statement.

This is the console output:

Describing Test-URLconnection
    [+] The URL status should be confirmed. 319ms
    [-] The URL status should be confirmed. 278ms
      HttpException: www.facebook.com cannot be accessed.
      at test-URLconnection<Begin>, <No file>: line 51
      at <ScriptBlock>, PATH: line 15
    [+] The URL status should be confirmed. 556ms
Tests completed in 1.54s
Tests Passed: 2, Failed: 1, Skipped: 0, Pending: 0, Inconclusive: 0 

Can one use an if/else-statement with Pester?


Solution

  • I followed the advise from Mark Wragg and created a separate Context for testing errors with the following code.

    Context "Test cases which fail" {
            $Error.Clear()
            $countCases = @(
                @{'url' = 'www.asdfasf.com'}
                @{'url' = 'www.facebook.com'}
            )
            It "The correct Error message should be thrown" -TestCases $countCases{
                param($url)
                    { test-URLconnection -URL $url } | Should -Throw -ExceptionType ([System.Web.HttpException])
            }
        }
    

    A small hint, I was quite struggling with the ExceptionType catch. Keep in mind to wrap the function in curly braces. Otherwise, it was failing for me.