Search code examples
powershellunit-testingpester

How to write Pester Unit Test for ranges of values with multiple decimals


I have a PowerShell function that returns value with multiple decimals from a range of values. How do I write Pester unit test for this kind of function. This kind of function is used to check version of some of applications like Outlook.

function randomVersion{
    $randomVersion= Get-Random -InputObject '14.1.3.5397', '14.2.3.5399', '15.4.2.1327', '15.5.2.1328', '16.3.7.9437', '16.7.7.9438'
    return $randomVersion
}

Solution

  • Any way you like, depending on what exactly you want to test - Pester is Powershell code, so you could do a regex match on the string pattern:

    randomVersion | should -Match -RegularExpression '^(14|15|16)\.[0-9]+\.[0-9]+\.[0-9]+$'
    

    Or you could write more code around it to test more things, e.g.

    function randomVersion
    {
        Get-Random -InputObject '1', 'test', '14.1.3.5397', '14.2.3.5399', '15.4.2.1327', '15.5.2.1328', '16.3.7.9437', '16.7.7.9438'
    }
    
    Import-Module -Name Pester
    
    Describe "Tests for randomVersion" {
    
        It "works" {
    
            $result = randomVersion 
    
            $version = $result -as [version]
            $version | Should -not -BeNullOrEmpty
    
            if ($version)
            {
                $version.Major | Should -BeIn 14, 15, 16
            }
        }
    }