我可以在Pester中使用If / Else语句吗?

时间:2019-09-05 12:45:30

标签: powershell powershell-5.0 pester

我想测试一个函数是否成功,但是也要在失败时抛出正确的错误。

我写了一个函数Test-URLconnection,该函数应该测试URL是否可访问,否则将引发错误。

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

我希望这两个测试能够通过,因为即使无法通过Invoke-WebRequest(我在Test-URLconnection中使用的命令)访问Facebook,它也应该被else语句捕获了。

这是控制台输出:

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 

有人可以在Pester中使用if / else语句吗?

1 个答案:

答案 0 :(得分:0)

我遵循Mark Wragg的建议,并使用以下代码创建了单独的上下文来测试错误。

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

一个小提示,我在ExceptionType捕获方面颇为挣扎。请记住将函数包装在花括号中。否则,这对我来说是失败的。