1

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
}
  • ... what is it that you want to test, exactly? That it returns anything? That it returns a string with a pattern of numbers and dots? That it returns a set value from some specific allowed values? That it returns a known Outlook version? – TessellatingHeckler Aug 01 '18 at 23:55
  • I want to test that it returns any one of the versions starting from either 14.x.x,xxxx, or 15.x.x.xxxx, or 16.x.x.xxxx. – Coding Enthusiast Aug 02 '18 at 00:00
  • 1
    Well, to be honest you should have written the test first then written a function that makes the test pass... – EBGreen Aug 02 '18 at 00:00
  • Your comment suggests one way to do it. Just use a `Should -MatchExactly` with a regex for the items in your comment. – EBGreen Aug 02 '18 at 00:05
  • @TessellatingHeckler `^1[456]\.\d+\.\d+\.\d+$` cleaner – Maximilian Burszley Aug 02 '18 at 01:29
  • @TheIncorrigible1 if you want to allow version numbers like `'14.୩೦.১๓.໒' -match '^1[456]\.\d+\.\d+\.\d+$'`, sure. – TessellatingHeckler Aug 02 '18 at 01:40
  • Do you anticipate his hard-coded list of randoms will match that? – Maximilian Burszley Aug 02 '18 at 01:42
  • @TheIncorrigible1 "*used to check version of some of applications like Outlook*" - if Outlook localised to Bengali doesn't return version numbers in Bengali Unicode digits, I'll be most disappointed in Microsoft. Although, if it does, your regex will be more suitable for it. ;) – TessellatingHeckler Aug 02 '18 at 01:47

1 Answers1

3

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
        }
    }
}
TessellatingHeckler
  • 27,511
  • 4
  • 48
  • 87