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:

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:

~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的更多相关文章

  1. 学习笔记之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 ...

  2. 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 ...

  3. Unit Testing with NSubstitute

    These are the contents of my training session about unit testing, and also have some introductions a ...

  4. [Java Basics3] XML, Unit testing

    What's the difference between DOM and SAX? DOM creates tree-like representation of the XML document ...

  5. Javascript单元测试Unit Testing之QUnit

    body{ font: 16px/1.5em 微软雅黑,arial,verdana,helvetica,sans-serif; }           QUnit是一个基于JQuery的单元测试Uni ...

  6. [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 ...

  7. C/C++ unit testing tools (39 found)---reference

    http://www.opensourcetesting.org/unit_c.php API Sanity AutoTest Description: An automatic generator ...

  8. Unit Testing a zend-mvc application

    Unit Testing a zend-mvc application A solid unit test suite is essential for ongoing development in ...

  9. VS2010(2012)中使用Unit Testing进行单元测试

    原文 VS2010(2012)中使用Unit Testing进行单元测试 使用VS 2012自带的Unit Testing工具进行单元测试是非常方便的.网上关于这方面的例子很多,这篇随笔只起个人学习笔 ...

随机推荐

  1. Webdriver API (一)

    (转载) 1.1  下载selenium2.0的包 官方download包地址:http://code.google.com/p/selenium/downloads/list 官方User Guid ...

  2. 【译】 AWK教程指南 附录D-AWK的内置变量

    因内置变量的个数不多,此处按其相关性分类说明,并未按其字母顺序排列. ARGC ARGC表示命令行上除了选项 -F, -v, -f 及其所对应的参数之外的所有参数的个数.若将"awk程序&q ...

  3. C语言断言

    1.概述 断言是对某种假设条件进行检查(可理解为若条件成立则无动作,否则应报告),它可以快速发现并定位软件问题,同时对系统错误进行自动报警.断言可以对在系统中隐藏很深,用其它手段极难发现的问题进行定位 ...

  4. HDU 4714 Tree2cycle

    Tree2cycle dfs 不是根节点:如果边数大于等于2,则删除与父节点的边.并且是一条环,那么每个点的度数是2,则还要删除num(每个节点儿子数)-2,只留两个儿子.当然删除边的儿子也要连到环上 ...

  5. 【noip模拟】考试总结

    今天睡了14个小时啊 把一星期的觉都补回来了 要不是被叫醒了 我肯定还在睡觉- - 其实现在还想睡... 集训真是伤身啊 感觉再睡就要睡成sb了 鉴于昨天被完虐(真·完虐 怒垫底) 来写篇总结 得分: ...

  6. HDU-4662 MU Puzzle 水题

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4662 倒推考虑长度就可以了. //STATUS:C++_AC_31MS_240KB #include ...

  7. Java TreeMap 源码解析

    继上篇文章介绍完了HashMap,这篇文章开始介绍Map系列另一个比较重要的类TreeMap. 大家也许能感觉到,网络上介绍HashMap的文章比较多,但是介绍TreeMap反而不那么多,这里面是有原 ...

  8. semget() semop()

    semget() 可以使用系统调用semget()创建一个新的信号量集,或者存取一个已经存在的信号量集: 系统调用:semget();原型:intsemget(key_t key,int nsems, ...

  9. HDU 1018 Big Number

    LINK:HDU 1018 题意:求n!的位数~ 由于n!最后得到的数是十进制,故对于一个十进制数,求其位数可以对该数取其10的对数,最后再加1~ 易知:n!=n*(n-1)*(n-2)*...... ...

  10. 三、servlet如何配置

    生命周期 可以第一次请求时就实例化,也可以web容器启动时就实例化 WebServlet(loadOnStartUp=1) <loadOnStartUp.../> 直接收整型值,越小优先级 ...