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. Oracle数据库中truncate命令和delete命令的区别

    首先讲一下,truncate命令: 语法:TRUNCATE  TABLE  table; 表格里的数据被清空,存储空间被释放. 运行后会自动提交,包括之前其它未提交的会话,因而一旦清空无法回退. 只有 ...

  2. NOIP2010 引水入城

    4引水入城 题目描述 在一个遥远的国度,一侧是风景秀美的湖泊,另一侧则是漫无边际的沙漠.该国的行政区划十分特殊,刚好构成一个N 行M 列的矩形,如上图所示,其中每个格子都代表一座城市,每座城市都有一个 ...

  3. git ssh key for github

    第一:检查.ssh是否存在(ls -al ~/.ssh) $ ls -al ~/.ssh Lists the files in your .ssh directory, if they exist 第 ...

  4. 【原】lua的table深拷贝

    一般写的时候要注意以下几个问题: 1.自己里面的属性是自己,要防止死循环 2.同一个table地址出现在table属性(k或者v)的不同地方,复制时不能复制成2个table地址,需与原来地址保持一致 ...

  5. jsp?echo

  6. HDU 3488--Tour(KM or 费用流)

    因为每个点只能经过一次 所以考虑拆点 这题有坑,有重边.. KM算法 把一个点拆成入点和出点 入点在X部,出点在Y步. 如果u,v之间有路径,就在X部的u点连接Y部的v点 求完美匹配. 当完美匹配的时 ...

  7. 5A的肖特基二极管 SK5x / SK5xx

    5A的肖特基 管压降经实测2A/0.3V, SK5x 和SK5xx别在于前者是四位命名,后者是一个五位命名带B, 封装不一样,参数基本一致.不细看手册容易用错了. 四位命名:封装为SMC (DO-21 ...

  8. angular的filter

    angular的filter filter两种用法 1.在模板中使用filter {{expression|filter}}//基本用法 {{expression|filter1|filter2|fi ...

  9. Delphi- 一些H8记录

    CheckOrder方法写在uDataModConn类里.

  10. 我的JS 类 写法

    长这样! var p,p1; //构造函数 function Person(name) { this.name = name; } //原型对象 var proto = { getName : fun ...