如何纠缠测试 class 模块 (.psm1) 中的方法?

How to Pester-test a method in a class module (.psm1)?

我已经写了多个 classes。所有这些都可以互换使用。主脚本(Main.ps1)导入其中一些并运行程序。

我想为我创建的这些 class 个模块 (.psm1) 中的每一个创建 Pester 测试,包括它们的方法。

class MyClass
{
    [string]GetID()
    {
        [string]$id = New-Guid
        return $id
    }
}

如何导入 MyClass,以及如何在 Pester 中模拟 New-Guid

创建一个包含如下内容的纠缠脚本MyClass.GetID.Tests.ps1

using module ".\MyClass.psm1"

Describe "GetID() method flows" {
    InModuleScope "MyClass" {
        $mockObject = [MyClass]::new()
        $mockGuid   = "guid"

        Mock New-Guid { 
            return $mockGuid 
        }

        Context "Happy flow" {
            It "Should return the guid" {
                $result = $mockObject.GetID()
                $result | Should -Be $mockGuid

                Assert-MockCalled New-Guid -Scope It -Exactly 1
            }
        }
    }
}

您还可以 dot-source class 模块:

. ".\MyClass.psm1"

Describe "GetID() method flows" {
    BeforeAll {
        $mockObject = [MyClass]::new()
        $mockGuid   = "guid"

        Mock New-Guid { 
            return $mockGuid 
        }
    }

    Context "Happy flow" {
        It "Should return the guid" {
            $result = $mockObject.GetID()
            $result | Should -Be $mockGuid

            Assert-MockCalled New-Guid -Scope It -Exactly 1
        }
    }
}

当然也可以从同一个测试脚本中测试所有方法。 请注意,PowerShell 无法卸载 class。这意味着对 class 的更改通常在您重新启动 PowerShell 会话之前不可用。