|
| 1 | +--- |
| 2 | +applyTo: '**/*.tests.ps1' |
| 3 | +description: 'PowerShell Pester testing best practices based on Pester v5 conventions' |
| 4 | +--- |
| 5 | + |
| 6 | +# PowerShell Pester v5 Testing Guidelines |
| 7 | + |
| 8 | +This guide provides PowerShell-specific instructions for creating automated tests using PowerShell Pester v5 module. Follow PowerShell cmdlet development guidelines in [powershell.instructions.md](./powershell.instructions.md) for general PowerShell scripting best practices. |
| 9 | + |
| 10 | +## File Naming and Structure |
| 11 | + |
| 12 | +- **File Convention:** Use `*.tests.ps1` naming pattern |
| 13 | +- **Placement:** Place test files next to tested code or in dedicated test directories |
| 14 | +- **No Direct Code:** Put ALL code inside Pester blocks (`BeforeAll`, `Describe`, `Context`, `It`, etc.) |
| 15 | +- **Skipping Tests:** For tests that require specific conditions (e.g., OS, elevated privileges), create a helper function within `BeforeDiscovery` block to check conditions and set a variable (e.g., `$isElevated`) that can be used with `-Skip` on test blocks. |
| 16 | + |
| 17 | +## Test Structure Hierarchy |
| 18 | + |
| 19 | +```powershell |
| 20 | +Describe 'FunctionName or FeatureName' { |
| 21 | + BeforeDiscovery { |
| 22 | + # Setup that runs before any tests are discovered |
| 23 | + } |
| 24 | + BeforeAll { |
| 25 | + # Common helper functions or variables |
| 26 | + } |
| 27 | + Context 'When condition' { |
| 28 | + BeforeAll { |
| 29 | + # Setup for context |
| 30 | + } |
| 31 | + It 'Should behavior' { |
| 32 | + # Individual test |
| 33 | + } |
| 34 | + AfterAll { |
| 35 | + # Cleanup for context |
| 36 | + } |
| 37 | + } |
| 38 | +} |
| 39 | +``` |
| 40 | + |
| 41 | +## Core Keywords |
| 42 | + |
| 43 | +- **`Describe`**: Top-level grouping, typically named after function being tested |
| 44 | +- **`Context`**: Sub-grouping within Describe for specific scenarios |
| 45 | +- **`It`**: Individual test cases, use descriptive names |
| 46 | +- **`Should`**: Assertion keyword for test validation |
| 47 | +- **`BeforeAll/AfterAll`**: Setup/teardown once per block |
| 48 | +- **`BeforeEach/AfterEach`**: Setup/teardown before/after each test |
| 49 | + |
| 50 | +## Setup and Teardown |
| 51 | + |
| 52 | +- **`BeforeAll`**: Runs once at start of containing block, use for expensive operations |
| 53 | +- **`BeforeEach`**: Runs before every `It` in block, use for test-specific setup |
| 54 | +- **`AfterEach`**: Runs after every `It`, guaranteed even if test fails |
| 55 | +- **`AfterAll`**: Runs once at end of block, use for cleanup |
| 56 | +- **Variable Scoping**: `BeforeAll` variables available to child blocks (read-only), `BeforeEach/It/AfterEach` share same scope |
| 57 | + |
| 58 | +## Assertions (Should) |
| 59 | + |
| 60 | +- **Basic Comparisons**: `-Be`, `-BeExactly`, `-Not -Be` |
| 61 | +- **Collections**: `-Contain`, `-BeIn`, `-HaveCount` |
| 62 | +- **Numeric**: `-BeGreaterThan`, `-BeLessThan`, `-BeGreaterOrEqual` |
| 63 | +- **Strings**: `-Match`, `-Like`, `-BeNullOrEmpty` |
| 64 | +- **Types**: `-BeOfType`, `-BeTrue`, `-BeFalse` |
| 65 | +- **Files**: `-Exist`, `-FileContentMatch` |
| 66 | +- **Exceptions**: `-Throw`, `-Not -Throw` |
| 67 | + |
| 68 | +## Mocking |
| 69 | + |
| 70 | +- **`Mock CommandName { ScriptBlock }`**: Replace command behavior |
| 71 | +- **`-ParameterFilter`**: Mock only when parameters match condition |
| 72 | +- **`-Verifiable`**: Mark mock as requiring verification |
| 73 | +- **`Should -Invoke`**: Verify mock was called specific number of times |
| 74 | +- **`Should -InvokeVerifiable`**: Verify all verifiable mocks were called |
| 75 | +- **Scope**: Mocks default to containing block scope |
| 76 | + |
| 77 | +```powershell |
| 78 | +Mock Get-Service { @{ Status = 'Running' } } -ParameterFilter { $Name -eq 'TestService' } |
| 79 | +Should -Invoke Get-Service -Exactly 1 -ParameterFilter { $Name -eq 'TestService' } |
| 80 | +``` |
| 81 | + |
| 82 | +## Test Cases (Data-Driven Tests) |
| 83 | + |
| 84 | +Use `-TestCases` or `-ForEach` for parameterized tests: |
| 85 | + |
| 86 | +```powershell |
| 87 | +It 'Should return <Expected> for <Input>' -TestCases @( |
| 88 | + @{ Input = 'value1'; Expected = 'result1' } |
| 89 | + @{ Input = 'value2'; Expected = 'result2' } |
| 90 | +) { |
| 91 | + Get-Function $Input | Should -Be $Expected |
| 92 | +} |
| 93 | +``` |
| 94 | + |
| 95 | +## Data-Driven Tests |
| 96 | + |
| 97 | +- **`-ForEach`**: Available on `Describe`, `Context`, and `It` for generating multiple tests from data |
| 98 | +- **`-TestCases`**: Alias for `-ForEach` on `It` blocks (backwards compatibility) |
| 99 | +- **Hashtable Data**: Each item defines variables available in test (e.g., `@{ Name = 'value'; Expected = 'result' }`) |
| 100 | +- **Array Data**: Uses `$_` variable for current item |
| 101 | +- **Templates**: Use `<variablename>` in test names for dynamic expansion |
| 102 | + |
| 103 | +```powershell |
| 104 | +# Hashtable approach |
| 105 | +It 'Returns <Expected> for <Name>' -ForEach @( |
| 106 | + @{ Name = 'test1'; Expected = 'result1' } |
| 107 | + @{ Name = 'test2'; Expected = 'result2' } |
| 108 | +) { Get-Function $Name | Should -Be $Expected } |
| 109 | +
|
| 110 | +# Array approach |
| 111 | +It 'Contains <_>' -ForEach 'item1', 'item2' { Get-Collection | Should -Contain $_ } |
| 112 | +``` |
| 113 | + |
| 114 | +## Tags |
| 115 | + |
| 116 | +- **Available on**: `Describe`, `Context`, and `It` blocks |
| 117 | +- **Filtering**: Use `-TagFilter` and `-ExcludeTagFilter` with `Invoke-Pester` |
| 118 | +- **Wildcards**: Tags support `-like` wildcards for flexible filtering |
| 119 | + |
| 120 | +```powershell |
| 121 | +Describe 'Function' -Tag 'Unit' { |
| 122 | + It 'Should work' -Tag 'Fast', 'Stable' { } |
| 123 | + It 'Should be slow' -Tag 'Slow', 'Integration' { } |
| 124 | +} |
| 125 | +
|
| 126 | +# Run only fast unit tests |
| 127 | +Invoke-Pester -TagFilter 'Unit' -ExcludeTagFilter 'Slow' |
| 128 | +``` |
| 129 | + |
| 130 | +## Skip |
| 131 | + |
| 132 | +- **`-Skip`**: Available on `Describe`, `Context`, and `It` to skip tests |
| 133 | +- **Conditional**: Use `-Skip:$condition` for dynamic skipping |
| 134 | +- **Runtime Skip**: Use `Set-ItResult -Skipped` during test execution (setup/teardown still run) |
| 135 | + |
| 136 | +```powershell |
| 137 | +It 'Should work on Windows' -Skip:(-not $IsWindows) { } |
| 138 | +Context 'Integration tests' -Skip { } |
| 139 | +``` |
| 140 | + |
| 141 | +## Error Handling |
| 142 | + |
| 143 | +- **Continue on Failure**: Use `Should.ErrorAction = 'Continue'` to collect multiple failures |
| 144 | +- **Stop on Critical**: Use `-ErrorAction Stop` for pre-conditions |
| 145 | +- **Test Exceptions**: Use `{ Code } | Should -Throw` for exception testing |
| 146 | + |
| 147 | +## Best Practices |
| 148 | + |
| 149 | +- **Descriptive Names**: Use clear test descriptions that explain behavior |
| 150 | +- **AAA Pattern**: Arrange (setup), Act (execute), Assert (verify) |
| 151 | +- **Isolated Tests**: Each test should be independent |
| 152 | +- **Avoid Aliases**: Use full cmdlet names (`Where-Object` not `?`) |
| 153 | +- **Single Responsibility**: One assertion per test when possible |
| 154 | +- **Test File Organization**: Group related tests in Context blocks. Context blocks can be nested. |
| 155 | +- **Operating System Specific Tests**: Use `-Skip` with conditions to skip tests on unsupported platforms (e.g., `-Skip:(-not $IsWindows)` for Windows-only tests). |
| 156 | +- **Elevated Privileges**: For tests requiring admin rights, use this example function with `-Skip` to conditionally skip if not elevated: |
| 157 | + |
| 158 | +```powershell |
| 159 | +BeforeDiscovery { |
| 160 | + $isElevated = if ($IsWindows) { |
| 161 | + ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole( |
| 162 | + [Security.Principal.WindowsBuiltInRole]::Administrator) |
| 163 | + } else { |
| 164 | + $false |
| 165 | + } |
| 166 | +} |
| 167 | +``` |
| 168 | + |
| 169 | +## Example Test Pattern |
| 170 | + |
| 171 | +```powershell |
| 172 | +Describe 'Windows Service set tests' -Skip:(!$IsWindows) { |
| 173 | + BeforeDiscovery { |
| 174 | + $isAdmin = if ($IsWindows) { |
| 175 | + $identity = [Security.Principal.WindowsIdentity]::GetCurrent() |
| 176 | + $principal = [Security.Principal.WindowsPrincipal]$identity |
| 177 | + $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) |
| 178 | + } |
| 179 | + else { |
| 180 | + $false |
| 181 | + } |
| 182 | + } |
| 183 | +
|
| 184 | + BeforeAll { |
| 185 | + $resourceType = 'Microsoft.Windows/Service' |
| 186 | + # Use the Print Spooler service for set tests — it exists on all Windows |
| 187 | + # machines and is safe to reconfigure briefly. |
| 188 | + $testServiceName = 'Spooler' |
| 189 | +
|
| 190 | + function Get-ServiceState { |
| 191 | + param([string]$Name) |
| 192 | + $json = @{ name = $Name } | ConvertTo-Json -Compress |
| 193 | + $out = $json | dsc resource get -r $resourceType -f - 2>$testdrive/error.log |
| 194 | + $LASTEXITCODE | Should -Be 0 -Because (Get-Content -Raw $testdrive/error.log) |
| 195 | + return ($out | ConvertFrom-Json).actualState |
| 196 | + } |
| 197 | + } |
| 198 | +
|
| 199 | + Context 'Input validation' -Skip:(!$isAdmin) { |
| 200 | + BeforeAll { |
| 201 | + $script:originalState = Get-ServiceState -Name $testServiceName |
| 202 | + } |
| 203 | +
|
| 204 | + AfterAll { |
| 205 | + # Restore original logon account |
| 206 | + if ($script:originalState -and $script:originalState.logonAccount) { |
| 207 | + $restoreJson = @{ |
| 208 | + name = $testServiceName |
| 209 | + logonAccount = $script:originalState.logonAccount |
| 210 | + } | ConvertTo-Json -Compress |
| 211 | + $restoreJson | dsc resource set -r $resourceType -f - 2>$testdrive/error.log |
| 212 | + } |
| 213 | + } |
| 214 | +
|
| 215 | + It 'Fails when name is not provided' { |
| 216 | + $json = @{ startType = 'Manual' } | ConvertTo-Json -Compress |
| 217 | + $out = $json | dsc resource set -r $resourceType -f - 2>&1 |
| 218 | + $LASTEXITCODE | Should -Not -Be 0 |
| 219 | + } |
| 220 | + } |
| 221 | +} |
| 222 | +``` |
| 223 | + |
| 224 | +**Key Sections**: Run (Path, Exit), Filter (Tag, ExcludeTag), Output (Verbosity), TestResult (Enabled, OutputFormat), CodeCoverage (Enabled, Path), Should (ErrorAction), Debug |
0 commit comments