Search code examples
unit-testingpowershellenumspester

Pester and testing for enum


How do I test for enum with the Powershell unit test framework Pester?

What I get back from the testee seems to be a string and not my proper enum.


Testresult

The test results in an error. What I got back was Apple and not my enum [FruitType]::Apple.

...
Expected {[FruitEnum]::Apple}, but got {Apple}.
6:         $res.TheFruit | Should -Be [FruitEnum]::Apple
...

Fruit.psm1

The Powershell module here makes the enum "public" and exports a method that returns an object with my Fruit enum.

enum FruitEnum{
    Apple
}
function Get-Fruit{
    return @{
        TheFruit = [FruitEnum]::Apple
    }
}
Export-ModuleMember -Function Get-Fruit

Fruit.Tests.ps1

The Pester test calls using to get hold of the enum, calls the testee and checks the result.

using module .\Fruit.psm1
Import-Module .\Fruit.psm1 -Force
Describe "Get-Fruit" {
        It "returns an enum" {
        $res = Get-Fruit
        $res.TheFruit | Should -Be [FruitEnum]::Apple
    }
}

Solution

  • I have occasionally seen odd things with Pester, and used a trick such as the following to fix them:

    ($res.TheFruit -eq [FruitEnum]::Apple) | Should Be True
    

    That is, perform the comparison and then check that the result is True, rather than trust that Should will be able to assert that something coming down the pipeline is the Type that you expect it to be.

    Another check you could do is to verify the Type of the object:

    $res.TheFruit.GetType().Fullname | Should Be "FruitEnum"