My Technical Notes

Wednesday, 8 February 2017

PowerShell: Extremely Basic Unit Testing Module

Below is the code for an extremely basic module that can be used for unit testing. There are two functions defined, `Assert-AreEqual` and `Assert-IsTrue`:


$Script:colorOf = { param($b) if ($b) { 'Green' } else { 'Red' } };
$Script:statusOf = { param($b) if ($b) { 'passed' } else { 'failed' } };

Function Assert-AreEqual {

    param($Expected, $Actual, [string]$Message, [switch]$StopOnFailure)

    Write-Host "$Script:Tahir";

    $passed = $Expected -eq $Actual;
    $color = & $Script:colorOf $passed;
    $status = & $Script:statusOf $passed;

    $writeHost = { param($s) Write-Host $s -ForegroundColor $color; }

    if ($Message) {
        &$writeHost "Assert-AreEqual: [$Message] $status";
    } else {
        &$writeHost "Assert-AreEqual: $status";
    }

    if (-not $passed) {
        &$writeHost "Expected: $Expected";
        &$writeHost "Actual: $Actual";
        &$writeHost "*********************************************";

        if ($StopOnFailure) {
            throw "Assert-AreEqual: $(if ($Message) { "[$Message] " } else { '' } ) stopping on failure";
        }
    }
}

Function Assert-IsTrue {
    param([bool]$Condition, [string]$Message, [switch]$StopOnFailure)

    $color = & $Script:colorOf $Condition;
    $status = & $Script:statusOf $Condition;

    $writeHost = { Write-Host $args[0] -ForegroundColor $color; }

    if ($Message) {
        &$writeHost "Assert-IsTrue: [$Message] $status";
    } else {
        &$writeHost "Assert-IsTrue: $status";
    }

    if (-not $Condition) {
        &$writeHost "*********************************************";

        if ($StopOnFailure) {
            throw "Assert-IsTrue: $(if ($Message) { "[$Message] " } else { '' } ) stopping on failure";
        }
    }
}

Export-ModuleMember Assert-*

You use the module in pretty much the same way as `Assert.AreEqual` and `Assert.IsTrue` are used when unit testing in C#.

For instance, if you expect something will be `true`, use `Assert-IsTrue`. Use the message parameter, so you can keep track of assertions:


Assert-IsTrue $cond "Useful identifying message";

If you want to check the equality of two things, use `Assert-AreEqual`:


Assert-AreEqual $expectedObj $actualObj "Useful identifying message";

No comments: