Unit Testing PowerShell Code with Pester

时间:2022-08-31 21:25:51

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:

Unit Testing PowerShell Code with Pester

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:

Unit Testing PowerShell Code with Pester

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:

Unit Testing PowerShell Code with Pester

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. NoSQL初探之人人都爱Redis:(4)Redis主从复制架构初步探索

    一.主从复制架构简介 通过前面几篇的介绍中,我们都是在单机上使用Redis进行相关的实践操作,从本篇起,我们将初步探索一下Redis的集群,而集群中最经典的架构便是主从复制架构.那么,我们首先来了解一 ...

  2. ajaxFileUpload文件上传

    一.简介 ajaxFileUpload是一种异步的文件上传控件,通过ajax进行文件上传,并获取上传处理结果.在很多时候我们需要使用到文件上传的功能,但是不需要使用那些强大的上传插件.此时就可以使用a ...

  3. .tostring()格式化大全

    C 货币 2.5.ToString("C") ¥2.50 D 十进制数 25.ToString("D5") 00025 E 科学型 25000.ToString ...

  4. wc移植sae笔记

    1.wc移植到sae---上传图片 ①先看profile.ptl.html中的ajax代码修改functions.js中G_BASE_URL的值.在这里我先写死成->'http://2.idan ...

  5. Docker学习笔记之一,搭建一个JAVA Tomcat运行环境

    Docker学习笔记之一,搭建一个JAVA Tomcat运行环境 前言 Docker旨在提供一种应用程序的自动化部署解决方案,在 Linux 系统上迅速创建一个容器(轻量级虚拟机)并部署和运行应用程序 ...

  6. objective-C学习笔记(二)类 class 和 结构 struct

    Objective-C的类型 引用类型 类 class 指针 pointer 块 block 值类型 基础数值类型 结构 struct 枚举 enum 类型装饰 协议 protocol 类别 cate ...

  7. SVN 在 Xcode中的状态说明

    最近同事总是问我关于SVN状态的问题,‘C’是什么意思啦?‘A’是什么意思啦?等等一系列问题. 为了方便以后查阅,以及新同事的快速融入,特在此记录一下^_^. 当然了大家也可以google一下,一搜一 ...

  8. 【noip】华容道

    描述 小 B 最近迷上了华容道,可是他总是要花很长的时间才能完成一次.于是,他想到用编程来完成华容道:给定一种局面,华容道是否根本就无法完成,如果能完成,最少需要多少时间. 小 B 玩的华容道与经典的 ...

  9. operator重载运算符

    1.重载运算符的函数一般格式如下 函数类型    operator  运算符名称    (形参表列) {对运算符的重载处理} 例如,想将"+"用于Complex(复数)的加法运算, ...

  10. Android下DrawerLayout的使用

    Android下DrawerLayout的使用 DrawerLayout见名知意,就是一个具有抽屉效果的布局,看看这个效果图,是不是感觉很炫酷 这么炫的效果其实不一定非要用类似一些SlidingMen ...