【问题标题】:Should -Throw Method in PowerShellPowerShell 中的 should -Throw 方法
【发布时间】:2021-07-15 15:34:52
【问题描述】:

我正在尝试在 PowerShell 中运行一些测试,以检查 SolutionInfo.cs 文件中的版本是否格式正确、是否丢失或是否正常。

通过我的测试,我试图涵盖这些场景。其中一个用于检查文件,当版本正常时,正在通过,但其余的都失败了。此外,我将向您发送脚本和测试。解决方案文件包含版本。有人可以帮我解决这两种情况吗?throw 方法或适合我的情况的任何其他方法应该是什么样子?

function Get-VersionFromSolutionInfoFile($path) {
    try {
        [Version]$version = (Get-Content -Raw $path) -replace '(?s).*\bAssemblyVersion\("(.*?)"\).*', '$1'        
    } 
    catch {    
        throw "Missing version or incorrect format."
    }
    return $version.ToString()
}

it "returns version from SolutionInfo.cs file"{
    Get-VersionFromSolutionInfoFile("$pwd/SolutionInfo.cs")  | Should -Be '1.0.0.0'
}
it "returns exception if there aren't any versions in the file"{
    Get-VersionFromSolutionInfoFile("$pwd/SolutionInfo2.cs")  | Should -Throw 
}
    it "returns exception if the version is not in the correct format"{
    Get-VersionFromSolutionInfoFile("$pwd/SolutionInfo3.cs")  | Should -Throw
}

【问题讨论】:

    标签: powershell pester


    【解决方案1】:

    当使用Should -Throw时,你需要提供一个脚本块作为输入,所以你的测试需要如下:

    it "returns exception if there aren't any versions in the file"{
        { Get-VersionFromSolutionInfoFile("$pwd/SolutionInfo2.cs") }  | Should -Throw 
    }
        it "returns exception if the version is not in the correct format"{
        { Get-VersionFromSolutionInfoFile("$pwd/SolutionInfo3.cs") }  | Should -Throw
    }
    

    您还应该将-ErrorAction Stop 添加到您的Get-Content。这可确保您的 Catch 被触发,因为它强制异常终止:

    function Get-VersionFromSolutionInfoFile($path) {
        try {
            [Version]$version = (Get-Content -Raw $path -ErrorAction Stop) -replace '(?s).*\bAssemblyVersion\("(.*?)"\).*', '$1'        
        } 
        catch {    
            throw "Missing version or incorrect format."
        }
        return $version.ToString()
    }
    

    【讨论】:

      猜你喜欢
      • 2020-10-21
      • 1970-01-01
      • 2013-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-16
      • 2020-02-10
      • 1970-01-01
      相关资源
      最近更新 更多