PowerShell unit tests with Pester

Few days ago I have discover interesting PowerShell module Pester for creating unit tests in PowerShell. As a code for testing is used PowerShell script from my previous post dedicated to password generation. PowerShell module Pester is installed using command:

Install-Module -Name Pester -Force -SkipPublisherCheck


Udemy course: Improve your productivity with PowerShell

Installed PowerShell modules can be listed by:

Get-InstalledModule

Unit test of New-AzureSqlPassword.ps1 script is saved to New-AzureSqlPassword.Tests.ps1 file and has following code:

Describe "New-AzureSqlPassword" {
    It "Should return password 32 characters long" {
        $password = .\New-AzureSqlPassword.ps1
        $password.Length | Should -Be 32
    }

    Context "Password complexity" {
        It "Should contain lowercase letters" {
            $password = .\New-AzureSqlPassword.ps1
            $measure = $password.GetEnumerator() | Where-Object { [System.Char]::IsLower($_) } | Measure-Object 
            $measure.Count | Should -BeGreaterThan 0
        }

        It "Should contain uppercase letters" {
            $password = .\New-AzureSqlPassword.ps1
            $measure = $password.GetEnumerator() | Where-Object { [System.Char]::IsUpper($_) } | Measure-Object 
            $measure.Count | Should -BeGreaterThan 0
        }

        It "Should contain digits" {
            $password = .\New-AzureSqlPassword.ps1
            $measure = $password.GetEnumerator() | Where-Object { [System.Char]::IsDigit($_) } | Measure-Object 
            $measure.Count | Should -BeGreaterThan 0
        }

        It "Should contain special characters" {
            $password = .\New-AzureSqlPassword.ps1
            $measure = $password.GetEnumerator() | Where-Object { ($_ -eq '!') -or ($_ -eq '$') -or ($_ -eq '#') -or ($_ -eq '%') } | Measure-Object 
            $measure.Count | Should -BeGreaterThan 0
        }
    }

    Context "Password difference" {
        It "Should return different passwords when calling two times" {
            $password1 = .\New-AzureSqlPassword.ps1
            $password2 = .\New-AzureSqlPassword.ps1
            $password1 -eq $password2 | Should -BeFalse
        }
    }
}

PowerShell script and it’s unit test is placed in the same folder:

PowerShell command line

Unit test is run using command:

Invoke-Pester

Output of unit test is:

PowerShell command line

If you are interested in PowerShell automation, take my Udemy course Improve your productivity with PowerShell.