20 Pestering your script

 

Pester is a powerful tool for automating your testing in PowerShell scripts. As we transition into a DevOps-oriented world, it becomes crucial to ensure the reliability of your scripts. No one wants a broken script running in a production environment. Even if you test your script initially, modifications or unique conditions might arise that require retesting. This chapter will delve into automated unit testing for PowerShell scripts using Pester.

20.1 The vision

Here’s where we want to get you:

  1. You write some code or modify some old code.
  2. You check your code into a source control repository.
  3. The repository triggers a continuous integration pipeline. Usually incorporating third-party tools, the pipeline builds a virtual machine to test your script. The pipeline copies your script into the virtual machine and runs several automated tests. If the tests fail, you get an email telling you what happened.
  4. If the tests pass, your code is deployed to a deployment repository (maybe PowerShellGallery.com or a private repository), making it available for production.

Step 3 in this list, called “The Miracle,” is entirely automated. To enable The Miracle, you must contribute an automated testing mechanism to your code. This way, any code revisions can be quickly retested, ensuring its functionality before deployment.

20.2 Problems with manual testing

20.3 Benefits of automated testing

20.4 Introducing Pester

20.5 Coding to be tested

20.6 What do you test?

20.6.1 Integration tests

20.6.2 Unit tests

20.6.3 Don’t test what isn’t yours

20.7 Writing a basic Pester test

20.7.1 Creating a fixture