The Pester Book Chapter Review (9)

Table of ContentsTest Cases

It’s a chapter like this, if you didn’t know it before, that you suddenly realize how much more powerful Pester is than you may have first thought. Test cases allow us to reuse an It block multiple times. Each time we use it, we can pass in different values that we want our parameter(s) to have, and record what happens when each of those are used. This might be confusing in text alone, so let me show you an example that I came up with.

Clear-Host
Describe -Name 'add two numbers:' {
    $TestCases = @(
        @{Number1 = 1; Number2 = 1; Total = 2; TestName = '1 + 1'}
        @{Number1 = 2; Number2 = 2; Total = 4; TestName = '2 + 2'}
        @{Number1 = 3; Number2 = 3; Total = 6; TestName = '3 + 3'}
        @{Number1 = 4; Number2 = 4; Total = 8; TestName = '4 + 4'}
        @{Number1 = 5; Number2 = 5; Total = 10; TestName = '5 + 5'}
    )
 
    It -Name 'Testing addition of two numbers <TestName>:' -TestCases $TestCases {
        Param ($Number1,$Number2,$Total)
        $Number1 + $Number2 | Should -Be $Total 
    } # End It.
} # End Describe.

I’ll quickly point out a few things we learned in this chapter: We’re now using a new It parameter called TestCases. This parameter accepts an array of hash tables, Yes, you read that correctly, and each one is tested against the It block. In our example, two of the hash table’s key-value pairs serve as the values to the Param block. The TestName value, however, ends up being stuffed into the It block’s Name parameter, allowing us to differentiate between which test is which.

Here’s the results the above code produces.

Describing add two numbers:
  [+] Testing addition of two numbers '1 + 1': 52ms
  [+] Testing addition of two numbers '2 + 2': 10ms
  [+] Testing addition of two numbers '3 + 3': 25ms
  [+] Testing addition of two numbers '4 + 4': 28ms
  [+] Testing addition of two numbers '5 + 5': 32ms

It is a chapter such as this, and even Pester on its own, that make you realize that you have to have some sort of grounding in PowerShell function writing to be successful. And maybe not function writing, maybe script writing as well, providing you understand how to include parameters in your code. It’s important you’re comfortable with PowerShell long before you tackle Pester — just putting that out there.

Next is Mocks; can’t wait!

Update: I made a slight change to the above code. While it produces the same results, what I did was this. Instead of calculating the Total inside the It block, we send in what the total should be as the Total parameter value. This ensures that if the Number1 or Number2 parameter values are changed, that the test actually fails. When the total is calculated in the It block, it’s always going to pass, and I didn’t want that to be the case.

2 thoughts on “The Pester Book Chapter Review (9)

Leave a Reply

Your email address will not be published. Required fields are marked *