Unit Testing PowerShell Code with Pester
Summary: Guest blogger, Dave Wyatt, discusses using Pester to analyze small pieces of Windows PowerShell code.
Note This is a five-part series that includes the following posts:
- What is Pester and Why Should I Care?
Learn about a new test framework for PowerShell called Pester - Getting Started with Pester
Learn how to get information back from Pester - Unit Testing PowerShell Code with Pester
Use Pester to analyze small pieces of Windows PowerShell code - Testing Script Modules with Pester
Use Pester for testing PowerShell modules - More Pester Features and Resources
Learn about more Pester resources
Before we get into the technical details today, let’s define a few terms. There are several categories of automated testing, all of which are used in a continuous delivery pipeline. For the purposes of Windows PowerShell code, I tend to refer to three:
- Unit tests
- Integration tests
- Acceptance tests
Unit tests
A unit test is the smallest and fastest type, and it is the first thing that will be run in your pipeline. It can usually be executed on the developer’s machine before checking in the code to source control. Unit tests are responsible for verifying the behavior of a single unit of code, which in PowerShell, typically means a function.
If the function you are testing depends on anything other than the parameters that are passed in, you’ll want to isolate your code from those other dependencies in the unit test. These dependencies could be anything, including a web service of some sort, the state of the computer where the script runs, or even calls to other PowerShell functions or cmdlets.
Integration tests
Integration tests are pretty much the opposite of unit tests. Instead of isolating your code from the other parts, you run everything in all its glory, and make sure it’s behaving properly when all of the bits are working together. This might require you to set up a more complicated test environment, so the necessary web services, for example, are available. This means that integration tests are more expensive to run. It’s for this reason that you only move on to integration tests if the unit tests have already passed.
Acceptance tests
Acceptance tests are fundamentally the same as integration tests, except they refer to tests that you run after your code is deployed into production. You can use them as a quick sanity check to make sure everything’s up and running. You might also hear these referred to as “smoke tests.”
The examples of Pester that you’ve seen so far are perfect for integration or acceptance tests. They make calls to an API (without caring what its internals do), and write test cases against the results. For a unit test, though, we need some way of isolating our function under test from its dependencies. That’s where mocking comes into play.
Pester has a built-in mocking framework that allows you to create dummy versions of other PowerShell commands. A picture is worth a thousand words, so here’s a sample of a PowerShell function that needs some mocking to be properly unit tested:
This is a fairly simple function, but it contains calls to four other cmdlets: Get-Date, Get-ADUser, Where-Object, and Disable-ADAccount. Of these, we can ignore Where-Object because it’s simply a logic construct—and indeed, it is what we’re testing. (The function is written this way instead of using the better Search-ADAccount cmdlet simply to give us more to work within the Pester examples.)
To test this code without requiring an actual Active Directory domain, we need to consider a few things:
- Make Get-Date return a specific date and time. (This is optional, but not a bad idea.)
- Make Get-ADUser return a set of test objects. We want some of these to be “disabled,” and others should be left alone. The test cases will make sure the proper objects are passed to Disable-ADAccount.
- Make Disable-ADAccount do nothing, other than give us a way to track how it was called, so we know which users would be disabled.
Here’s what this might look like:
In this example, we’re seeing two new Pester commands: Mock and Assert-MockCalled. When you use Mock, you temporarily replace the behavior of a PowerShell command with whatever you want it to be. Mock is active only inside the Describe or Context block where it is defined. If we had another Describe block in the example, Get-Date, Get-ADUser, and Disable-ADAccount would go back to their normal behavior. When Mock was called on Disable-ADAccount, we didn’t even bother to specify an implementation; it defaults to doing nothing.
In my experience, most mocks fall into one of these two categories: You either want them to return objects that your tests define, or you want them to do nothing (and then later verify how they were called). I can’t think of a situation where I’ve had a mock return output later and be verified via the Assert-MockCalled command because those tests would be redundant.
There are a few things to notice about mocking…
- Notice that I didn’t need to specify any parameter blocks for my mocks—and indeed, you should not even try to do that. This is because Pester will examine the original command that’s being mocked, and it will inject its parameters (including dynamic parameters) into the mock for you automatically.
- The Mock and Assert-MockCalled commands have a parameter called –ParameterFilter. This allows you to control under what circumstances the mock is effective (or whether the assertion should succeed or fail), based on the parameters that are used when the mock is called. Incidentally, you can mock the same command multiple times, with different parameter filters and different implementations, if you need to.
- Mocking works by taking advantage of the command resolution order in Windows PowerShell, as detailed in theabout_Command_Precedence Help file. When multiple PowerShell commands exist with the same name, the function version will be executed instead of cmdlets or external commands. When you define a mock in Pester, it creates a function with the name of the command that you want to mock, and that will be what gets executed instead of the original command.
It’s important to understand how this works, because your scripts might need some small modifications to work well with mocking in Pester. For example, let’s revise our Active Directory example slightly:
In this version, the calls to Get-ADUser and Disable-ADAccount have been module-qualified (in ActiveDirectory\Get-ADUser). This gives PowerShell some extra information about which command to execute, and causes it to skip your mocked command and execute the live commands instead.
To make the code friendly to mocking, you’d need to remove the module-qualified calls. Or you can wrap those calls in your own internal function, which can be mocked instead of the Active Directory cmdlets. Wrapping code into a function to facilitate mocking is a pretty common occurrence, such as if you want to mock calls to a .NET class or method (which Pester can’t do).
There are other nuances to the Mock and Assert-MockCalled commands, some of which we’ll talk about tomorrow when we look at unit testing code in script modules. To find more help and information about Pester, see:
- Pester Help files
- Pester Home page and Pester Powershell BDD style testing framework on GitHub
- Pester Group on Google
~Dave
Thanks, Dave!
I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.
Unit Testing PowerShell Code with Pester的更多相关文章
- 学习笔记之Unit testing/Integration testing/dotnet test and xUnit
source code https://github.com/haotang923/dotnet/tree/master/src Unit testing C# code in .NET Core u ...
- 10 Unit Testing and Automation Tools and Libraries Java Programmers Should Learn
转自:https://javarevisited.blogspot.com/2018/01/10-unit-testing-and-integration-tools-for-java-program ...
- Unit Testing with NSubstitute
These are the contents of my training session about unit testing, and also have some introductions a ...
- [Java Basics3] XML, Unit testing
What's the difference between DOM and SAX? DOM creates tree-like representation of the XML document ...
- Javascript单元测试Unit Testing之QUnit
body{ font: 16px/1.5em 微软雅黑,arial,verdana,helvetica,sans-serif; } QUnit是一个基于JQuery的单元测试Uni ...
- [Unit Testing] AngularJS Unit Testing - Karma
Install Karam: npm install -g karma npm install -g karma-cli Init Karam: karma init First test: 1. A ...
- C/C++ unit testing tools (39 found)---reference
http://www.opensourcetesting.org/unit_c.php API Sanity AutoTest Description: An automatic generator ...
- Unit Testing a zend-mvc application
Unit Testing a zend-mvc application A solid unit test suite is essential for ongoing development in ...
- VS2010(2012)中使用Unit Testing进行单元测试
原文 VS2010(2012)中使用Unit Testing进行单元测试 使用VS 2012自带的Unit Testing工具进行单元测试是非常方便的.网上关于这方面的例子很多,这篇随笔只起个人学习笔 ...
随机推荐
- [Tommas] 测试用例覆盖率(二)
二.详细用例的设计 划分好了测试项,接着就是针对各个测试项,考虑具体的测试用例了.根据测试项的特点,测试用例的设计角度也有所不同.下面我们就来看看通常的功能点测试用例,该从哪些角度出发来进行设计: 1 ...
- [King.yue]Ext中Grid得到选择行数据的方法总结
(1)grid.getStore().getRange(0,store.getCount()); //得到grid所有的行 (2)grid.getSelectionModel().getSele ...
- sqlserver 2008 R2 分区表测试
有一张表期中有100多w条数据 程序执行起来比较慢,想用分区表的办法,使查询变快一些. 方案如下 --查看分区信息SELECT * FROM sys.partition_range_values -- ...
- gSoap的 “error LNK2001: 无法解析的外部符号 _namespaces”解决方法
gSoap是C/C++开发webService服务第三方的公开类库. 出现上述错误是因为缺少必要的头文件导致的. 在用wsdl2h生成头文件的时候,一并生成了类似 xx.nsmap 的文件,这个文件实 ...
- 各类JavaScript插件
ZeroClipboard复制内容到剪切板(支持IE.FF.Chrome) ZeroClipboard.js ZeroClipboard.swf hotkeys键盘监听 jquery.hotkeys. ...
- uvalive 4728 Squares
题意:求所有正方形中两点距离最大值的平方值. 思路:旋转卡壳法. 分别用数组和vector存凸包时,旋转卡壳代码有所不同. #include<cstdio> #include<cma ...
- 关于T公司的强矩阵架构的思考
我所在的T公司是强矩阵架构,关于这类公司,应该是不少大公司的主流架构,也就是说一个职员在公司内不仅在项目内有相应的级别,在其行政上也是有相应的级别,日常工作以项目的内容为主,但是同时也是属于行政的一员 ...
- 【原创】tcp协议那块一些点(想到了再加)
1.3次握手 4次握手 2.那张状态图,FIN_WAIT主动关闭方,CLOSE_WAIT被动关闭方 主动关闭方发出FIN后进入FIN_WAIT,FIN_WAIT方收到了ACK和FIN,发出了ACK,则 ...
- POJ1038 - Bugs Integrated, Inc.(状态压缩DP)
题目大意 要求你在N*M大小的主板上嵌入2*3大小的芯片,不能够在损坏的格子放置,问最多能够嵌入多少块芯片? 题解 妈蛋,这道题折腾了好久,黑书上的讲解看了好几遍才稍微有点眉目(智商捉急),接着看了网 ...
- Java & XML Tool Overview
As mentioned in the introduction Sun now provides these tools for XML Processing in Java: StAX Reade ...