Unit Tests for PowerShell with Pester (finally there!): The Setup and First Tests


The aim is of this tutorial🔍 is the introduction of Pester — the unit testing framework for Powershell

1. Install Pester

  • I use chocolatey

2. File Name

  • test file needs to be called *.tests.ps1

3. BDD inspired syntax

  • The basic snippet for unit tests I am using is

The describe-driven inspiration for syntax can be largely attributed be traced back to Ruby land and the well known RSpec Ruby test framework. This nested style is usually called “BDD Style” for “Behavior driven development”.

— From 2 A first unit test — The Art of Unit Testing, Third Edition MEAP V04

4. Structure: USE AAA

  • names of the whole test block is important as you should get from the test output all information
  • USE AAA is the acronym combining the naming needed for the block
  • U for the Unit of work (function, usually) describe
  • S for scenario, usually introduced by the word given...
  • E for expectation, usually introduced by words it should...
  • AAA is a traditional structure of the inner workings of a unit test
  • A for arrange — set up all bindings necessary (inputs) to call the function
  • A for act — call the function with a given input at its entry point
  • A for assert — test the function at one of its exit points

5. Should statement and its switches

  • before running Should function, you need
  • arrange the tests by configuring proper inputs
  • act to run the unit to obtain the result
  • Should is combined with many built-in switches that are good to know
  • for value
  • checks to see if a file contains the specified text
  • note that the input is either an object or a path string

6. Sources

Technical Support Engineer of a Data Collection Platform (Snowplow Analytics)