Using Pester

Pester is used to test PowerShell's scripts and functions. It can be used for the unit testing of templates as well.

Pester provides the necessary infrastructure to ease the process of writing unit tests in PowerShell. It provides facilities to write test cases, execute, and report back results. It is an open source utility available as a PowerShell module. By default, it is available in Windows Server 2016 and Windows 10. For other operating systems, it can be installed using the following:

 Install-Module cmdlet

Writing unit tests using Pester is quite simple. It provides functions for declaring tests, as well as assertions. Assertions refer to the process of comparing and validating two variables. A simple Pester script in PowerShell is shown next. In this example, unit tests are written against a simple function that adds two numbers together.

Pester provides the Describe function for defining a test suite. It contains multiple test cases. It takes a string value to describe the test suite. The BeforeAll function is the first function executed and typically used for initializing the test suite. It is here that variables are initialized and other conditions prepared as a starting position before individual unit tests are executed.

The actual tests are written using the It function. It takes a name and a script. The actual comparison between actual and expected values happens within this script. There are multiple assertions provided by Pester, and one of them is Should Be, which does an equality comparison. There are other Assertions defined here: https://github.com/pester/Pester/tree/master/Functions/Assertions.

The Context function is a placeholder function for distinguishing between different scenarios within the same test suite. There are two contexts in the next example—one of them contains a single test case and the other contains two test cases.

These tests can be executed using the invoke-pester cmdlet and passing the script as its parameter. They can also be executed on the PowerShell ISE Window directly:

function AddTwoNumbers([int] $a, [int] $b) {   
return $a + $b
}
$firstValue, $secondValue
Describe "Addition Validation Tests" {
BeforeAll {
$firstValue = 10
$secondValue = 20;
}
Context "using Global variables" {

It "Adding two positive numbers" {
AddTwoNumbers -a $firstValue -b $secondValue | Should Be 30
}
}
Context "Using Local Variables" {
It "Adding two positive numbers" {
$firstValue = 100
$secondValue = 200
AddTwoNumbers -a $firstValue -b $secondValue | Should Be 300
}
It "Adding two negative numbers" {
$firstValue = -100
$secondValue=-200
AddTwoNumbers -a $firstValue -b $secondValue | Should Be -300
}
}

}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.204.201