Day 53: Pester and Mocking

Welcome to Day 53 of the “100 Days of DevOps with PowerShell”! For background on our goals in this series, see Announcing the “100 Days of Devops with PowerShell” Series here at SCC.

Once you start to really get into testing your PowerShell scripts, you are going to want a mocking framework. A mocking framework enables you to provide a fake implementation of a function, along with logic that verifies how calls were made to the mocked function.  There are multiple mocking frameworks available in the community for general programming languages, such as Rhino and NMock. Visual Studio 2013 even shipped with its own mocking framework, called Microsoft Fakes.

Pester provides a mocking framework for PowerShell, I’m going to introduce one of the more impressive features in Pester. The Pester Mock command allows me to create new behavior for an existing command within the scope of a Describe or Context block.  I can use this to create functionality for a method that has not been coded, or to replace functionality in an existing method.

For example, I have the following basic function to test:

This is a very simple function that, when it is called, returns the number 42.  However, as you can see, the function has not been implemented yet.   I need to go ahead and create a unit test for this function. Here it is:

When I execute this unit test, it fails, as expected, because the function Return42 has not been coded yet.  But what if I want to make this unit test pass for now, even though the function is empty?  To do that, I need to “mock” up the function to return a value. By using the Mock command, I can create my own implementation of the function in my test, which replaces the default function:

If I execute this unit test, I can see that the test passes:

image

All I did was add one line to the unit test:

The above code says that if I make a call to Return42, it should return the value 42 instead of what the function is coded to do.  This allows me to control what values are used in my testing, and even test functions that have not been implemented.   You can even use mocking to replace existing PowerShell cmdlets, such as Write-Host, if you wanted.

This post is just to whet your appetite on what can be accomplished with mocking. For more information see the Pester Wiki.

Previous Installments

To see the previous installments in this series, visit “100 Days of DevOps with PowerShell”.

Leave a Reply