|
| 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 | +- **Import Pattern:** Use `BeforeAll { . $PSScriptRoot/FunctionName.ps1 }` to import tested functions |
| 15 | +- **No Direct Code:** Put ALL code inside Pester blocks (`BeforeAll`, `Describe`, `Context`, `It`, etc.) |
| 16 | + |
| 17 | +## Test Structure Hierarchy |
| 18 | + |
| 19 | +```powershell |
| 20 | +BeforeAll { # Import tested functions } |
| 21 | +Describe 'FunctionName' { |
| 22 | + Context 'When condition' { |
| 23 | + BeforeAll { # Setup for context } |
| 24 | + It 'Should behavior' { # Individual test } |
| 25 | + AfterAll { # Cleanup for context } |
| 26 | + } |
| 27 | +} |
| 28 | +``` |
| 29 | + |
| 30 | +## Core Keywords |
| 31 | + |
| 32 | +- **`Describe`**: Top-level grouping, typically named after function being tested |
| 33 | +- **`Context`**: Sub-grouping within Describe for specific scenarios |
| 34 | +- **`It`**: Individual test cases, use descriptive names |
| 35 | +- **`Should`**: Assertion keyword for test validation |
| 36 | +- **`BeforeAll/AfterAll`**: Setup/teardown once per block |
| 37 | +- **`BeforeEach/AfterEach`**: Setup/teardown before/after each test |
| 38 | + |
| 39 | +## Setup and Teardown |
| 40 | + |
| 41 | +- **`BeforeAll`**: Runs once at start of containing block, use for expensive operations |
| 42 | +- **`BeforeEach`**: Runs before every `It` in block, use for test-specific setup |
| 43 | +- **`AfterEach`**: Runs after every `It`, guaranteed even if test fails |
| 44 | +- **`AfterAll`**: Runs once at end of block, use for cleanup |
| 45 | +- **Variable Scoping**: `BeforeAll` variables available to child blocks (read-only), `BeforeEach/It/AfterEach` share same scope |
| 46 | + |
| 47 | +## Assertions (Should) |
| 48 | + |
| 49 | +- **Basic Comparisons**: `-Be`, `-BeExactly`, `-Not -Be` |
| 50 | +- **Collections**: `-Contain`, `-BeIn`, `-HaveCount` |
| 51 | +- **Numeric**: `-BeGreaterThan`, `-BeLessThan`, `-BeGreaterOrEqual` |
| 52 | +- **Strings**: `-Match`, `-Like`, `-BeNullOrEmpty` |
| 53 | +- **Types**: `-BeOfType`, `-BeTrue`, `-BeFalse` |
| 54 | +- **Files**: `-Exist`, `-FileContentMatch` |
| 55 | +- **Exceptions**: `-Throw`, `-Not -Throw` |
| 56 | + |
| 57 | +## Mocking |
| 58 | + |
| 59 | +- **`Mock CommandName { ScriptBlock }`**: Replace command behavior |
| 60 | +- **`-ParameterFilter`**: Mock only when parameters match condition |
| 61 | +- **`-Verifiable`**: Mark mock as requiring verification |
| 62 | +- **`Should -Invoke`**: Verify mock was called specific number of times |
| 63 | +- **`Should -InvokeVerifiable`**: Verify all verifiable mocks were called |
| 64 | +- **Scope**: Mocks default to containing block scope |
| 65 | + |
| 66 | +```powershell |
| 67 | +Mock Get-Service { @{ Status = 'Running' } } -ParameterFilter { $Name -eq 'TestService' } |
| 68 | +Should -Invoke Get-Service -Exactly 1 -ParameterFilter { $Name -eq 'TestService' } |
| 69 | +``` |
| 70 | + |
| 71 | +## Test Cases (Data-Driven Tests) |
| 72 | + |
| 73 | +Use `-TestCases` or `-ForEach` for parameterized tests: |
| 74 | + |
| 75 | +```powershell |
| 76 | +It 'Should return <Expected> for <Input>' -TestCases @( |
| 77 | + @{ Input = 'value1'; Expected = 'result1' } |
| 78 | + @{ Input = 'value2'; Expected = 'result2' } |
| 79 | +) { |
| 80 | + Get-Function $Input | Should -Be $Expected |
| 81 | +} |
| 82 | +``` |
| 83 | + |
| 84 | +## Data-Driven Tests |
| 85 | + |
| 86 | +- **`-ForEach`**: Available on `Describe`, `Context`, and `It` for generating multiple tests from data |
| 87 | +- **`-TestCases`**: Alias for `-ForEach` on `It` blocks (backwards compatibility) |
| 88 | +- **Hashtable Data**: Each item defines variables available in test (e.g., `@{ Name = 'value'; Expected = 'result' }`) |
| 89 | +- **Array Data**: Uses `$_` variable for current item |
| 90 | +- **Templates**: Use `<variablename>` in test names for dynamic expansion |
| 91 | + |
| 92 | +```powershell |
| 93 | +# Hashtable approach |
| 94 | +It 'Returns <Expected> for <Name>' -ForEach @( |
| 95 | + @{ Name = 'test1'; Expected = 'result1' } |
| 96 | + @{ Name = 'test2'; Expected = 'result2' } |
| 97 | +) { Get-Function $Name | Should -Be $Expected } |
| 98 | +
|
| 99 | +# Array approach |
| 100 | +It 'Contains <_>' -ForEach 'item1', 'item2' { Get-Collection | Should -Contain $_ } |
| 101 | +``` |
| 102 | + |
| 103 | +## Tags |
| 104 | + |
| 105 | +- **Available on**: `Describe`, `Context`, and `It` blocks |
| 106 | +- **Filtering**: Use `-TagFilter` and `-ExcludeTagFilter` with `Invoke-Pester` |
| 107 | +- **Wildcards**: Tags support `-like` wildcards for flexible filtering |
| 108 | + |
| 109 | +```powershell |
| 110 | +Describe 'Function' -Tag 'Unit' { |
| 111 | + It 'Should work' -Tag 'Fast', 'Stable' { } |
| 112 | + It 'Should be slow' -Tag 'Slow', 'Integration' { } |
| 113 | +} |
| 114 | +
|
| 115 | +# Run only fast unit tests |
| 116 | +Invoke-Pester -TagFilter 'Unit' -ExcludeTagFilter 'Slow' |
| 117 | +``` |
| 118 | + |
| 119 | +## Skip |
| 120 | + |
| 121 | +- **`-Skip`**: Available on `Describe`, `Context`, and `It` to skip tests |
| 122 | +- **Conditional**: Use `-Skip:$condition` for dynamic skipping |
| 123 | +- **Runtime Skip**: Use `Set-ItResult -Skipped` during test execution (setup/teardown still run) |
| 124 | + |
| 125 | +```powershell |
| 126 | +It 'Should work on Windows' -Skip:(-not $IsWindows) { } |
| 127 | +Context 'Integration tests' -Skip { } |
| 128 | +``` |
| 129 | + |
| 130 | +## Error Handling |
| 131 | + |
| 132 | +- **Continue on Failure**: Use `Should.ErrorAction = 'Continue'` to collect multiple failures |
| 133 | +- **Stop on Critical**: Use `-ErrorAction Stop` for pre-conditions |
| 134 | +- **Test Exceptions**: Use `{ Code } | Should -Throw` for exception testing |
| 135 | + |
| 136 | +## Best Practices |
| 137 | + |
| 138 | +- **Descriptive Names**: Use clear test descriptions that explain behavior |
| 139 | +- **AAA Pattern**: Arrange (setup), Act (execute), Assert (verify) |
| 140 | +- **Isolated Tests**: Each test should be independent |
| 141 | +- **Avoid Aliases**: Use full cmdlet names (`Where-Object` not `?`) |
| 142 | +- **Single Responsibility**: One assertion per test when possible |
| 143 | +- **Test File Organization**: Group related tests in Context blocks. Context blocks can be nested. |
| 144 | + |
| 145 | +## Example Test Pattern |
| 146 | + |
| 147 | +```powershell |
| 148 | +BeforeAll { |
| 149 | + . $PSScriptRoot/Get-UserInfo.ps1 |
| 150 | +} |
| 151 | +
|
| 152 | +Describe 'Get-UserInfo' { |
| 153 | + Context 'When user exists' { |
| 154 | + BeforeAll { |
| 155 | + Mock Get-ADUser { @{ Name = 'TestUser'; Enabled = $true } } |
| 156 | + } |
| 157 | +
|
| 158 | + It 'Should return user object' { |
| 159 | + $result = Get-UserInfo -Username 'TestUser' |
| 160 | + $result | Should -Not -BeNullOrEmpty |
| 161 | + $result.Name | Should -Be 'TestUser' |
| 162 | + } |
| 163 | +
|
| 164 | + It 'Should call Get-ADUser once' { |
| 165 | + Get-UserInfo -Username 'TestUser' |
| 166 | + Should -Invoke Get-ADUser -Exactly 1 |
| 167 | + } |
| 168 | + } |
| 169 | +
|
| 170 | + Context 'When user does not exist' { |
| 171 | + BeforeAll { |
| 172 | + Mock Get-ADUser { throw "User not found" } |
| 173 | + } |
| 174 | +
|
| 175 | + It 'Should throw exception' { |
| 176 | + { Get-UserInfo -Username 'NonExistent' } | Should -Throw "*not found*" |
| 177 | + } |
| 178 | + } |
| 179 | +} |
| 180 | +``` |
| 181 | + |
| 182 | +## Configuration |
| 183 | + |
| 184 | +Configuration is defined **outside** test files when calling `Invoke-Pester` to control execution behavior. |
| 185 | + |
| 186 | +```powershell |
| 187 | +# Create configuration (Pester 5.2+) |
| 188 | +$config = New-PesterConfiguration |
| 189 | +$config.Run.Path = './Tests' |
| 190 | +$config.Output.Verbosity = 'Detailed' |
| 191 | +$config.TestResult.Enabled = $true |
| 192 | +$config.TestResult.OutputFormat = 'NUnitXml' |
| 193 | +$config.Should.ErrorAction = 'Continue' |
| 194 | +Invoke-Pester -Configuration $config |
| 195 | +``` |
| 196 | + |
| 197 | +**Key Sections**: Run (Path, Exit), Filter (Tag, ExcludeTag), Output (Verbosity), TestResult (Enabled, OutputFormat), CodeCoverage (Enabled, Path), Should (ErrorAction), Debug |
0 commit comments