Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 34 ยท Real-World Use

Testing and Style with Pester

Test PowerShell with Pester 5: Describe, It, Should, BeforeAll, mocks and TestDrive, then lint with PSScriptAnalyzer and follow naming and style conventions.

A script that works today and breaks silently next month is a liability. The usual cure in every language is automated tests, and PowerShell has a standard tool for it: Pester. A second tool, PSScriptAnalyzer, reads your code without running it and points out risky or untidy patterns. Together with a few naming and style rules, they turn quick scripts into code a team can trust and change.

In this lesson you will learn how Pester 5 files are structured, the most useful Should assertions, how to replace commands with mocks, how to lint code, and the conventions the community follows. Pester and PSScriptAnalyzer need a PowerShell runtime, so their code is shown read-only. A small JavaScript test runner and a mock helper serve as stand-ins: they model the ideas (grouping, assertions, call counting) and are not Pester.

Windows PowerShell 5.1 ships with the old Pester 3.4. Install the current version with Install-Module Pester -Force -SkipPublisherCheck. Everything below is Pester 5 syntax, which is different in important ways from Pester 3.

What a Pester test file looks like

By convention a test file sits next to the code and ends in .Tests.ps1. It contains Describe blocks (what you test), optional Context blocks (a situation), and It blocks (one expectation each). Inside an It, you pipe a result into Should.

Suppose ConvertTo-Slug.ps1 defines a function that turns a title into a URL-friendly word list. The test file is:

POWERSHELL
# ConvertTo-Slug.Tests.ps1
BeforeAll {
    . $PSScriptRoot/ConvertTo-Slug.ps1       # load the code under test
}

Describe 'ConvertTo-Slug' {
    It 'lowercases and joins words with dashes' {
        ConvertTo-Slug -Text 'Hello Big World' | Should -Be 'hello-big-world'
    }

    It 'removes characters that are not letters or digits' {
        ConvertTo-Slug -Text 'C# & PowerShell!' | Should -Be 'c-powershell'
    }

    It 'throws when the text is empty' {
        { ConvertTo-Slug -Text '' } | Should -Throw
    }
}

Run it with Invoke-Pester -Path ./ConvertTo-Slug.Tests.ps1 -Output Detailed. Pester prints each It as passed or failed, with the expected and actual value of failed ones. In a build pipeline use Invoke-Pester -CI, which writes a test result file and sets a failing exit code when a test fails.

Note the braces around ConvertTo-Slug -Text '' in the last test. For -Throw you must pass a script block, otherwise the error happens before Should can look at it.

The Should assertions you will use most

Assertion Meaning
Should -Be 5 equal (strings compare case-insensitively)
Should -BeExactly 'Ada' equal, case-sensitive
Should -BeTrue / -BeFalse boolean checks
Should -BeNullOrEmpty nothing came back
Should -Contain 'x' a collection holds an item
Should -HaveCount 3 a collection has this many items
Should -Match 'regex' text matches a regular expression
Should -Throw a script block raises an error
Should -Not -Be 1 any assertion, negated

Use the most specific one. Should -HaveCount 3 tells you "expected 3 items but got 5", while Should -BeTrue on $list.Count -eq 3 can only say "expected true". Good messages save debugging time.

Discovery and run: the Pester 5 rule

The idea that surprises most newcomers is that Pester 5 runs a file in two phases. During discovery it executes your file to find all Describe, Context and It blocks, without running the bodies of It. During the run phase it executes BeforeAll, BeforeEach, the It bodies and the cleanup blocks. The consequence: code placed directly in a Describe block, outside BeforeAll or It, runs at discovery time and its variables are not visible inside the tests. Put setup in BeforeAll:

POWERSHELL
Describe 'Report' {
    BeforeAll {
        $rows = Import-Csv "$PSScriptRoot/sample.csv"      # run phase: visible in It
    }

    It 'reads three rows' {
        $rows | Should -HaveCount 3
    }
}

To generate several similar tests from data, use -ForEach (also called test cases) on an It, so each row becomes its own test with its own result:

POWERSHELL
It 'slugs <Text> as <Expected>' -ForEach @(
    @{ Text = 'One Two'; Expected = 'one-two' }
    @{ Text = 'A  B';    Expected = 'a-b' }
) {
    ConvertTo-Slug -Text $Text | Should -Be $Expected
}

Files without touching the disk: TestDrive

When code writes files, tests should not litter your real folders. Pester gives each Describe a temporary folder reachable through the TestDrive: drive, deleted after the run:

POWERSHELL
It 'writes a CSV report' {
    Export-Report -Path 'TestDrive:\report.csv'
    Test-Path 'TestDrive:\report.csv' | Should -BeTrue
}

Mocks: replace the outside world

Code that reads the clock, the registry, a service or a web API is hard to test, because the answer changes. A mock replaces a command inside the test, so it returns what you decide and records how it was called.

POWERSHELL
BeforeAll {
    . $PSScriptRoot/Get-DiskAlert.ps1
    Mock Get-PSDrive {
        [pscustomobject]@{ Name = 'C'; Used = 95GB; Free = 5GB }
    }
}

Describe 'Get-DiskAlert' {
    It 'warns when a drive is almost full' {
        Get-DiskAlert -ThresholdPercent 90 | Should -Match 'C: 95% full'
        Should -Invoke Get-PSDrive -Times 1 -Exactly
    }
}

Should -Invoke checks that the mocked command was called, how many times, and optionally with which parameters (-ParameterFilter { $Name -eq 'C' }). Put Mock in BeforeAll, BeforeEach or It, not loose in a Describe. Because mocks remove the real dependency, tests run fast and need no network, server or special rights.

The test loop

Arrange Set up data and mocks in BeforeAll.
Act Call the function inside It.
Assert Check the result with Should.

One It, one clear expectation.

1 / 2

A stand-in test runner

To see how groups, expectations and failure messages fit together, here is a very small runner. describe groups tests, it runs a body and catches failures, and expect(...).toBe() plays the role of Should -Be. It is a model, not Pester: the real tool has two phases, rich output and many more assertions.

JS Stand-in: a tiny test runner

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The last test fails on purpose so that you can see what a useful message looks like: it names both the expected and the actual value. Change "a b" to "a-b" and the run turns green.

A stand-in mock

A mock does two things: it returns a canned answer, and it remembers each call. This helper does the same for a function passed into the code under test. The real Mock replaces the command by name, with no change to your code.

JS Stand-in: a mock that counts calls

Press Run (or Ctrl + Enter) to see the console output here.

No output.

PSScriptAnalyzer: a linter for PowerShell

PSScriptAnalyzer checks scripts against a set of rules, with severity levels Information, Warning and Error. You install it once and point it at a file or folder:

POWERSHELL
Install-Module PSScriptAnalyzer -Scope CurrentUser
Invoke-ScriptAnalyzer -Path ./src -Recurse -Severity Warning, Error

Typical findings, and the fix for each:

Rule Why it matters Fix
PSAvoidUsingWriteHost Write-Host output cannot be captured or piped return objects, or Write-Verbose / Write-Information
PSAvoidUsingCmdletAliases gci, ?, % are hard to read in shared code use Get-ChildItem, Where-Object, ForEach-Object
PSUseApprovedVerbs names such as Fetch-Data break conventions rename to Get-Data (see Get-Verb)
PSAvoidUsingPlainTextForPassword a [string]$Password parameter exposes secrets use [securestring] or [pscredential]
PSUseShouldProcessForStateChangingFunctions Remove- or Set- functions should support -WhatIf add [CmdletBinding(SupportsShouldProcess)]
PSAvoidUsingInvokeExpression code injection risk, see Security and Secrets call the command directly

A settings file lets a team choose rules once. Pass it with -Settings:

POWERSHELL
# PSScriptAnalyzerSettings.psd1
@{
    Severity     = @('Error', 'Warning')
    ExcludeRules = @('PSAvoidUsingWriteHost')     # allowed in our console-only tools
}

When a rule is wrong for one function, suppress it narrowly with [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingWriteHost', '', Justification = 'Interactive menu')] rather than turning the rule off everywhere. Run both tools in your CI pipeline, so every change is checked.

Naming and style conventions

Consistent code is easier to read. These are the conventions most PowerShell teams use:

  • Verb-Noun names with an approved verb (Get-Verb lists them) and a singular noun: Get-ServerReport, not Fetch-ServerReports. See Cmdlets and the Verb-Noun Pattern.
  • PascalCase for functions and parameters (-ComputerName), and one consistent case for variables ($serverName or $ServerName, but not both).
  • Full command names in scripts. Aliases are fine at the prompt, but write Where-Object in a file.
  • Named parameters instead of positions when there are more than one or two arguments.
  • Splatting instead of backtick line continuations, which break when a space follows the backtick:
POWERSHELL
$params = @{
    Path    = $folder
    Filter  = '*.log'
    Recurse = $true
}
Get-ChildItem @params
  • Comment-based help (.SYNOPSIS, .PARAMETER, .EXAMPLE) on every public function, so Get-Help works. See Getting Help.
  • Return objects from functions and let the caller format them. Avoid Write-Host for data. See Formatting and Output.
  • Four-space indentation, the opening brace on the same line as the statement, and one function per file in modules.
  • Small functions that do one job, with [CmdletBinding()] and typed, validated parameters (Advanced Functions).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In Pester 5, where should you put setup code whose variables the It blocks need?

    Code loose in a Describe runs at discovery time, and its variables are not available when the It blocks run. BeforeAll runs in the run phase.
  2. 2. Why does a Should -Throw test wrap the call in braces?

    If you call the function directly, the error occurs before Should is reached and the test errors out. A script block lets Should run it and look for the exception.
  3. 3. What does a mock give you?

    A mock replaces a dependency inside the test, so the result is predictable and you can verify with Should -Invoke that it was called.
  4. 4. Which tool analyzes script code without running it?

    PSScriptAnalyzer is a static analysis tool (a linter). Pester runs your code in tests.
  5. 5. Which function name follows PowerShell conventions?

    Use an approved verb, a dash and a singular noun in PascalCase: Get-ServerReport.

Summary

  • Pester test files end in .Tests.ps1 and use Describe, Context and It; assertions use Should.
  • Pester 5 has a discovery phase and a run phase, so put setup in BeforeAll and generate cases with -ForEach.
  • TestDrive: gives tests a temporary disk, and Mock with Should -Invoke replaces and observes outside dependencies.
  • Invoke-ScriptAnalyzer finds risky and untidy code; settings files and narrow suppressions keep the rules practical.
  • Follow Verb-Noun naming with approved verbs, singular nouns, full command names, splatting, comment-based help and objects as output.
  • The JavaScript runner and mock are stand-ins for the ideas, not Pester itself.

Next: Project: Disk and Folder Report.