即使遇到异常,Pester也会失败测试

时间:2018-05-17 15:47:54

标签: powershell pester

我有一个专门处理异常并忽略它的实用程序函数,但是当用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

1 个答案:

答案 0 :(得分:1)

您看到的异常不是来自您的函数,而是来自您使用Remove-Item,这会导致错误尝试删除错误路径(也不存在) 。你应该删除它,因为你永远不会想到要创建项目。

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

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