05 / REUSABLE AUTOMATION · LESSON 20

Make confidence repeatable

Write and run two focused Pester tests.

16 min · learn at your pace

A check you can run again

Pester is a PowerShell testing framework. This lab bundles it, so you can write tests without installing a module.

Describe groups related checks, It names a particular behaviour, and Should asserts an expected result:

Describe 'Arithmetic' {
    It 'adds two numbers' {
        (2 + 3) | Should -Be 5
    }
}

Test a function

Put setup in BeforeAll and save tests in a file ending with .Tests.ps1. The supplied Math.ps1 defines Get-Double. Dot-source it in BeforeAll so each test can call the function.

BeforeAll { . '/home/user/Math.ps1' }

Run Invoke-Pester './Double.Tests.ps1' -PassThru. The returned result includes test counts and pass/fail information. -Output None suppresses Pester's display while retaining the result object.

You can write a multiline file from the editor using a single-quoted here-string: start with @' on its own line and end with '@ at the beginning of another line. Text inside stays literal, including dollar signs.

Test normal inputs and boundaries. A passing test gives evidence about the case you exercised, not a guarantee about every possible input.

Try an example.ps1
Invoke-Pester -Container (New-PesterContainer -ScriptBlock {
    Describe 'Arithmetic' {
        It 'adds correctly' { (2 + 3) | Should -Be 5 }
    }
}) -PassThru -Output None
YOUR TURN

Put it into practice.

Create Double.Tests.ps1 with two passing tests for Get-Double: 3 becomes 6, and 0 becomes 0. Load Math.ps1 in BeforeAll. Run the tests and return the Pester result using -PassThru -Output None.

See an explained solution
One way to solve it.ps1
@'
BeforeAll { . '/home/user/Math.ps1' }
Describe 'Get-Double' {
    It 'doubles a positive number' { Get-Double 3 | Should -Be 6 }
    It 'handles zero' { Get-Double 0 | Should -Be 0 }
}
'@ | Set-Content './Double.Tests.ps1'
Invoke-Pester './Double.Tests.ps1' -PassThru -Output None

The two tests cover a normal positive input and a boundary. Returning the Pester result allows another script to inspect the outcome.