When the input and output of a function are being repetitively tested, the TestCases parameter of It can be used. Test cases are defined in a hashtable, which is splatted into It as a set of parameters.
The four test cases used in the preceding example might be rewritten as follows:
Describe Get-SquareRoot {
It 'When the value is <Value>, the square root is <ExpectedResult>' -TestCases @( @{ Value = 1; ExpectedResult = 1 } @{ Value = 4; ExpectedResult = 2 } @{ Value = 9; ExpectedResult = 33 } @{ Value = 16; ExpectedResult = 44 } ) {
param (
$Value,
$ExpectedResult
)
Get-SquareRoot $Value | Should -Be $ExpectedResult
}
}
The preceding tests still contain errors; the advantage of this approach is that Pester will report a success or failure for each of the test cases individually:
Describing Get-SquareRoot
[+] Calculates the square root of 1 to be 1 52ms
[+] Calculates the square root of 4 to be 2 7ms
[-] Calculates the square root of 9 to be 33 10ms
Expected 33, but got 3.0000000000000000000000000000.
10: Get-SquareRoot $Value | Should -Be $ExpectedResult
[-] Calculates the square root of 16 to be 44 13ms
Expected 44, but got 4.000000000000000000000000000.
10: Get-SquareRoot $Value | Should -Be $ExpectedResult
Pester automatically replaces values enclosed in angular braces (< and >) with names from the hashtable describing each test case.
Using test cases can save time spent debugging code and tests, as fewer runs are needed to highlight problems.