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

Can I use If/Else statement in 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 

可以将 if/else-statement 与 Pester 一起使用吗?

我听从了 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 捕获时非常吃力。请记住将函数用花括号括起来。否则,它对我来说是失败的。