How to do NUnit assertions with PowerShell

Posted on 24.09.12


This blog post is the first in a series of posts which will cover my new PowerShell unit testing framework PsTest. The reason for covering NUnit assertions without any specific context will be made more clear in the later posts of the series. At the moment you may have a look at how NUnit assertions may be used in a real PsTest script here.

It is easy to use existing .NET libraries in PowerShell. If we want to do some assertions we may use the asserts provided by NUnit.

First lets make it really convenient to load the NUnit framework assembly (nunit.framework.dll) everytime we need it in PowerShell by making a simple module. Download NUnit and copy the framework assembly into a new folder named NUnit. Create a new module manifest file named NUnit.psd1 with the following content:

    ModuleVersion = '1.0'
    ModuleToProcess = 'NUnit.psm1'
    RequiredAssemblies = @( 'nunit.framework.dll' )

The module manifest instructs PowerShell to first load the required NUnit assembly and then a module file named NUnit.psm1. Create this module file in the same directory with the following content:

$Assert = [NUnit.Framework.Assert]
$Is = [NUnit.Framework.Is]

Export-ModuleMember -Variable Assert, Is

This will make sure that all static members of the NUnit.Framework.Assert and NUnit.Framework.Is  classes are easily available by using the variables $Assert and $Is. We export these variables when the module gets imported.

Your NUnit module directory should now look like this:

NUnit module directory.

Copy the new module directory into your PowerShell modules directory. In my case the modules directory is located at C:\Windows\System32\WindowsPowerShell\v1.0\Modules\. You can open your modules directory with PowerShell like this:

explorer.exe ($PSHOME | Join-Path -ChildPath Modules)

Check that the new NUnit module is set up correctly and available for import:

Get-Module -ListAvailable -Name NUnit
ModuleType Name                      ExportedCommands
---------- ----                      ----------------
Manifest   NUnit                     {}

Now import the module and check the imported variables:

Set-ExecutionPolicy -ExecutionPolicy remotesigned -Scope process
Import-Module -Name NUnit
(Get-Module -Name NUnit).ExportedVariables | Format-Table -AutoSize
Key    Value
---    -----
Assert System.Management.Automation.PSVariable
Is     System.Management.Automation.PSVariable

We are now ready to start asserting! Here are some samples:

$Assert::That(1, $Is::EqualTo(1))
$Assert::That($true, $Is::True)
$Assert::That('foo', $Is::EqualTo('bar'))
Exception calling "That" with "2" argument(s): "  String lengths are both 3. St
rings differ at index 0.
  Expected: "bar"
  But was:  "foo"
At line:3 char:14
+ $Assert::That <<<< ('foo', $Is::EqualTo('bar'))
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

And finally let us list all static members of $Assert and $Is:

$Assert |
    Get-Member -Static |
    Format-Wide -Column 4
AreEqual            AreNotEqual         AreNotSame          AreSame
ByVal               Catch               Contains            DoesNotThrow
Equals              Fail                False               Greater
GreaterOrEqual      Ignore              Inconclusive        IsAssignableFrom
IsEmpty             IsFalse             IsInstanceOf        IsInstanceOfType
IsNaN               IsNotAssignableFrom IsNotEmpty          IsNotInstanceOf
IsNotInstanceOfType IsNotNull           IsNotNullOrEmpty    IsNull
IsNullOrEmpty       IsTrue              Less                LessOrEqual
NotNull             Null                Pass                ReferenceEquals
That                Throws              True                Counter
$Is |
    Get-Member -Static |
    Format-Wide -Column 4
AssignableFrom      AssignableTo        AtLeast             AtMost
Equals              EqualTo             EquivalentTo        GreaterThan
GreaterThanOrEqu... InRange             InstanceOf          InstanceOfType
LessThan            LessThanOrEqualTo   ReferenceEquals     SameAs
SamePath            SamePathOrUnder     StringContaining    StringEnding
StringMatching      StringStarting      SubPath             SubsetOf
TypeOf              All                 BinarySerializable  Empty
False               NaN                 Negative            Not
Null                Ordered             Positive            True
Unique              XmlSerializable
Posted in: Uncategorized