Testing Powershell with Pester

Testing Powershell with Pester

Infrastructure as code is the gold standard that we want all our installations to achieve. That means that all machines in an environment can be correctly configured, torn down and rebuild consistently. However as anyone who provisioned VMs using cloud formation knows redeploying environments takes time. In many ways it feels like the bad old days when it took ages to build code. Our standard work day becomes code, build..... get coffee, read emails, do other things to fill time... then check the environment. If you have to do this even for the most innocuous changes to your scripts you start to lose the will. 

So if we are treating infrastructure as Code we need to test it like code. In the Powershell (Microsoft) world this is where Pester comes in. Pester is a Test framework that allows to you Mock out parts of a module or other methods. 

So for example if I had a module that called write host and I need to ensure that this happened I can "mock" write-host and ensure that is was called with the contents I expected. 

Essentially this is Unit testing, if you don't know what this is I suggest you have a look at Unit Testing definition on extreme programming. 

Pester using a very familiar syntax for defining the tests: 

Let run through key points in that structure:
- Describe: What am I going to be testing, in this case Test-TargetResource
- Context: This allows me to define variables or mocks over a number of tests. It also provides a nice way to logically group tests
- It: The test is self this is stating "It" should do this.
- Should: this is used to set the expectation for what the output is. If the test does not match the condition after should then the test is failed.

It is also worth noting that the Mock is created by stating:

Mock <FunctionName> { <Implementation> }
- Function Name: is the name of the function or method you need to mock i.e. in this instance Test-Path
- Implementation: the method body to be run in place of the overridden method

Pester is a fantastic additional to what is available within Powershell and can make all the difference when creating scripts that you are to reuse. Essentially you can prove your script without rebuilding an entire environment.

A Full example from the bits used in this post is available at: https://gist.github.com/john-nicholson/acf283f293d0cc90ad58 

Also it is worth checking out the Pester documentation: https://github.com/pester/Pester

About the author

John Nicholson

John Nicholson


Experienced Developer / Architect with a background in consultancy working with public and private sector client including Local Government Ombudsman, Legal Ombudsman, Virgin Atlantic and Willis Group

Microsoft Certified TrainerALMMicrosoft Certified Solutions Developer: Web ApplicationsProfessional Scrum Master

Read More