使用 Pester 5 和 PowerShell 7 模拟类函数 [英] Mocking class functions with Pester 5 and PowerShell 7
问题描述
有人有使用 Pester 5 和 PowerShell 7 模拟点源类函数的示例吗?
Does anyone have an example of mocking a dot-sourced class function with Pester 5 and PowerShell 7?
谢谢.
示例
Classes\MyClass.ps1:
Classes\MyClass.ps1:
class MyClass {
[void] Run() {
Write-Host "Class: Invoking run..."
}
}
MyModule.psm1:
MyModule.psm1:
# Import classes
. '.\Classes\MyClass.ps1'
# Instantiate classes
$MyClass = [MyClass]::new()
# Call class function
$MyClass.Run()
推荐答案
Pester 只模拟 命令 - 而不是类或其方法.
Pester only mocks commands - not classes or their methods.
模拟"的最简单方法用于方法分派测试的 PowerShell 类是利用 PowerShell 标记所有方法 virtual
的事实,从而允许派生类覆盖它们:
The easiest way to "mock" a PowerShell class for method dispatch testing is by taking advantage of the fact that PowerShell marks all methods virtual
, thereby allowing derived classes to override them:
class MockedClass : MyClass
{
Run() { Write-host "Invoking mocked Run()"}
}
这种方法的好处是将输入限制为 MyClass
类型的函数仍然可以使用模拟类型:
The nice thing about this approach is that functions that constrain input to the MyClass
type will still work with the mocked type:
function Invoke-Run
{
param([MyClass]$Instance)
$instance.Run()
}
$mocked = [MockedClass]::new()
Invoke-Run -Instance $mocked # this still works because [MockedClass] derives from [MyClass]
这篇关于使用 Pester 5 和 PowerShell 7 模拟类函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!