即使捕获异常,Pester 也无法通过测试

Pester fails test even when exception is caught

我有一个专门处理异常并忽略它的实用函数,但是当用 Pester 测试它时,测试失败,显示已经捕获并处理的异常。我是不是遗漏了什么,或者这是 Pester 中的错误?

此代码重现了问题:

function Test-FSPath {

    [cmdletbinding()]
    param([string]$FileSystemPath)

    if([string]::IsNullOrWhiteSpace($FileSystemPath)) { return $false }

    $result = $false
    try {  
        if(Test-Path $FileSystemPath) {
            Write-Debug "Verifying that $FileSystemPath is a file system path"
            $item = Get-Item $FileSystemPath -ErrorAction Ignore
            $result = ($item -ne $null) -and $($item.PSProvider.Name -eq 'FileSystem')        
        }
    } catch {
        # Path pattern that Test-Path / Get-Item can't handle 
        Write-Debug "Ignoring exception $($_.Exception.Message)" 
    }

    return ($result -or ([System.IO.Directory]::Exists($FileSystemPath)) -or ([System.IO.File]::Exists($FileSystemPath)))
}

Describe 'Test' {
    Context Test-FSPath { 
        It 'returns true for a path not supported by PowerShell Test-Path' {
            $absPath = "$env:TEMP\temp-file[weird-chars.txt"
            [System.IO.File]::WriteAllText($absPath, 'Hello world')
            $result = Test-FSPath $absPath -Debug
            $result | Should -Be $true 
            Write-Host "`$result = $result"
            Remove-Item $absPath
        } 
    }
}

预期结果:测试通过

实际结果:测试失败:

[-] returns true for a path not supported by PowerShell Test-Path 2.62s
  WildcardPatternException: The specified wildcard character pattern is not valid: temp-file[weird-chars.txt
  ParameterBindingException: Cannot retrieve the dynamic parameters for the cmdlet. The specified wildcard character pattern is not valid: temp-file[weird-chars.txt

您看到的异常不是来自您的函数,而是来自您对 Remove-Item 的使用,它抛出了试图删除错误路径(该路径也不存在)的错误。您应该删除它,因为您永远不会期望创建该项目。

或者,或者(如评论中所述)使用 TestDrive: 然后您无需担心清理(似乎要支持的路径需要使用 $Testdrive)。

    It 'returns true for a path not supported by PowerShell Test-Path' {
        $absPath = "$env:TEMP\temp-file[weird-chars.txt"
        [System.IO.File]::WriteAllText($absPath, 'Hello world')
        $result = Test-FSPath $absPath
        $result | Should -Be $true 
    } 

顺便说一句,我通常倾向于在 It 之外做一些执行类型的事情,只在里面测试结果。当我开始为您的代码执行此操作时,它告诉我测试通过了,因为错误随后转移到了 Context 块中。这就是我的意思(这个例子也是通过 $testdrive 变量使用 TestDrive:):

Describe 'Test' {
    Context Test-FSPath { 
        $absPath = "$testdrive\temp-file[weird-chars.txt"
        [System.IO.File]::WriteAllText($absPath, 'Hello world')
        $result = Test-FSPath $absPath

        It 'returns true for a path not supported by PowerShell Test-Path' {
            $result | Should -Be $true 
        } 
    }
}