Search code examples
powershellpester

Should -Throw Method in PowerShell


I am trying to run some test in PowerShell that will check if the version in SolutionInfo.cs file is correctly formatted, is it missing or is it okay.

With my tests I am trying to cover those scenarios. One of them for checking the file, when the version is okay, is passing but the rest is failing. In addition I am sending you the script and the tests. The solution files contain version. Can someone please help me with these two cases and how the throw method or any other that is fit for my case should look like?

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
}

Solution

  • When using Should -Throw you need to provide a scriptblock as input, so your tests need to be as follows:

    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
    }
    

    You should also add -ErrorAction Stop to your Get-Content. This ensures that your Catch is triggered, as it forces the exception to be terminating:

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