枚举的纠缠和测试

Los*_*nos 5 powershell enums unit-testing pester

enum如何使用 Powershell 单元测试框架Pester进行测试?

我从测试者那里得到的似乎是一个字符串,而不是我自己的enum


测试结果

测试结果出现错误。我得到的Apple不是我的 enum [FruitType]::Apple

...
Expected {[FruitEnum]::Apple}, but got {Apple}.
6:         $res.TheFruit | Should -Be [FruitEnum]::Apple
...
Run Code Online (Sandbox Code Playgroud)

水果.psm1

这里的 Powershell 模块将枚举设置为“公共”,并导出一个方法,该方法返回带有我的 Fruit 枚举的对象。

enum FruitEnum{
    Apple
}
function Get-Fruit{
    return @{
        TheFruit = [FruitEnum]::Apple
    }
}
Export-ModuleMember -Function Get-Fruit
Run Code Online (Sandbox Code Playgroud)

水果.测试.ps1

Pester 测试调用using以获取枚举,调用测试者并检查结果。

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
    }
}
Run Code Online (Sandbox Code Playgroud)

Cha*_*ynt 5

我偶尔会在 Pester 中看到一些奇怪的事情,并使用如下的技巧来解决它们:

($res.TheFruit -eq [FruitEnum]::Apple) | Should Be True
Run Code Online (Sandbox Code Playgroud)

也就是说,执行比较,然后检查结果是否为 True,而不是相信Should能够断言管道中的某些内容是您期望的类型。

您可以做的另一项检查是验证对象的类型:

$res.TheFruit.GetType().Fullname | Should Be "FruitEnum"
Run Code Online (Sandbox Code Playgroud)