Skip to content

66. Introduction to Pester

Note

The below information is extensively based in information taken from the PowerShell® Notes for Professionals book. I plan to extend this information based on my day to day usage of the language.

66.1: Getting Started with Pester

To get started with unit testing PowerShell code using the Pester-module, you need to be familiar with three keywords/commands:

  • Describe : Defines a group of tests. All Pester test files needs at least one Describe-block.
  • It : Defines an individual test. You can have multiple It-blocks inside a Describe-block.
  • Should : The verify/test command. It is used to define the result that should be considered a successful test.

Sample:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
Import-Module Pester
#Sample function to run tests against
function Add-Numbers{
  param($a, $b)
  return [int]$a + [int]$b
}
#Group of tests
Describe "Validate Add-Numbers" {
  #Individual test cases
  It "Should add 2 + 2 to equal 4" {
    Add-Numbers 2 2 | Should Be 4
  }
  It "Should handle strings" {
    Add-Numbers "2" "2" | Should Be 4
  }
  It "Should return an integer"{
    Add-Numbers 2.3 2 | Should BeOfType Int32
  }
}

Output:

1
2
3
4
Describing Validate Add-Numbers
[+] Should add 2 + 2 to equal 4 33ms
[+] Should handle strings 19ms
[+] Should return an integer 23ms