PowerShell CI Testing
A CI test is a check that runs code and reports pass or fail. The build fails when a check fails, so broken code does not ship.
Load the code with dot-sourcing
Dot-sourcing loads a script's functions into the current session. The test then calls them directly.
Set-Content -Path (Join-Path $PSScriptRoot "MathTools.ps1") -Value 'function Add-Numbers { param([int]$a, [int]$b) $a + $b }'
. (Join-Path $PSScriptRoot "MathTools.ps1")
Add-Numbers -a 3 -b 4A failing check prints a clear message
A check compares the real result with the expected result. A mismatch throws, and catch prints the failure.
Set-Content -Path (Join-Path $PSScriptRoot "MathTools.ps1") -Value 'function Add-Numbers { param([int]$a, [int]$b) $a + $b }'
. (Join-Path $PSScriptRoot "MathTools.ps1")
$result = Add-Numbers -a 2 -b 2
try {
if ($result -ne 7) { throw "Expected 7, got $result" }
"PASS: addition"
} catch {
"FAIL: " + $_.Exception.Message
}A native failure sets LASTEXITCODE
The native command false always fails. Its exit code is 1, so the build prints FAILED.
false
if ($LASTEXITCODE -ne 0) { "BUILD FAILED" } else { "BUILD PASSED" }Example
Set-Content -Path (Join-Path $PSScriptRoot "MathTools.ps1") -Value 'function Add-Numbers { param([int]$a, [int]$b) $a + $b }'
. (Join-Path $PSScriptRoot "MathTools.ps1")
$passed = 0
try {
if ((Add-Numbers -a 3 -b 4) -ne 7) { throw "Addition failed" }
$passed++
"PASS: addition"
} catch {
"FAIL: " + $_.Exception.Message
}
try {
if ((Add-Numbers -a 10 -b -3) -ne 7) { throw "Addition failed" }
$passed++
"PASS: addition with a negative number"
} catch {
"FAIL: " + $_.Exception.Message
}
"Tests passed: $passed"Key points
- Test: a check that compares a real result with an expected result.
- Use dot-sourcing to load a script's functions into the current session.
- Use try/catch to turn a failed check into a clear failure message.
- LASTEXITCODE: the number the last native command returned, where 0 means success.
- Use an if statement on LASTEXITCODE to print BUILD FAILED when a native command fails.
In this example, the test script is created and dot-sourced, then two checks run inside try/catch blocks. Each passing check raises the count and prints a PASS line, and the last line prints the total.
Note
A test script never starts a second PowerShell session to test code. It loads the code in the same session.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does dot-sourcing a test script do?