Pester is a great module for testing your PowerShell scripts and modules. It has great mocking support, a test drive for setting up isolated files and supports a lot of assertions. Since the importance of PowerShell growths, testing your scripts is a must.
This is part 2 of the series “Develop next level PowerShell with Visual Studio and Pester”. It assumes that you have a Visual Studio solution with a basic Pester Test in GitHub.
Pester basics
If you create a new test in Visual Studio, it looks like this:
Describe "PowerShellTest1" {
Context "Exists" {
It "Runs" {
}
}
}
As you can see you have three levels:
Describe: This is the name of the test displayed in test explorer. It is not ONE test in the test results. It’s more a container scope for many tests that executes as a unit.
Context: Like “Describe” the Context is a container for tests. You can mock functions or have test files in the scope of a context.
It: “It” is the actual test. You add an assertion here to test the state of your system. “It” is also a scope for mocking like context.
You can use these elements to structure your tests in a BDD style after the GivenWhenThen pattern.
$project = (Split-Path -Parent $MyInvocation.MyCommand.Path).Replace(".Tests", "")
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path).Replace(".tests.", ".")
. "$project\$sut"
Describe "AnswerToUltimateQuestion" {
Context "Given an enormous supercomputer named Deep Thought, when we ask the ultimate question about life, the universe, and everything" {
It "should return 42" {
AnswerToUltimateQuestion | Should Be 42
}
}
}
Continue reading “Use Pester to author your PowerShell scripts”