[英]Mocking class functions with Pester 5 and PowerShell 7
Does anyone have an example of mocking a dot-sourced class function with Pester 5 and PowerShell 7?有没有人有 mocking 点源 class function 与纠缠 5 和 PowerShell 7 的示例?
Thank you.谢谢你。
Edit: example编辑:例子
Classes\MyClass.ps1:类\MyClass.ps1:
class MyClass {
[void] Run() {
Write-Host "Class: Invoking run..."
}
}
MyModule.psm1:我的模块.psm1:
# Import classes
. '.\Classes\MyClass.ps1'
# Instantiate classes
$MyClass = [MyClass]::new()
# Call class function
$MyClass.Run()
Pester only mocks commands - not classes or their methods. Pester 只模拟命令——而不是类或它们的方法。
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: “模拟” PowerShell class 进行方法分派测试的最简单方法是利用 PowerShell 标记所有方法
virtual
的事实,从而允许派生类覆盖它们:
class MockedClass : MyClass
{
Run() { Write-host "Invoking mocked Run()"}
}
The nice thing about this approach is that functions that constrain input to the MyClass
type will still work with the mocked type:这种方法的好处是,将输入约束到
MyClass
类型的函数仍可用于模拟类型:
function Invoke-Run
{
param([MyClass]$Instance)
$instance.Run()
}
$mocked = [MockedClass]::new()
Invoke-Run -Instance $mocked # this still works because [MockedClass] derives from [MyClass]
Does anyone have an example of mocking a dot-sourced class function with Pester 5 and PowerShell 7?
有没有人有 mocking 点源 class function 与纠缠 5 和 PowerShell 7 的示例?
You can look at this repo: https://github.com/dsccommunity/SqlServerDsc/blob/8dde54df19ccbdb95629ec1c074e7a97acf229d2/tests/Unit/Classes/ResourceBase.Tests.ps1#L111-L165你可以看看这个回购协议: https://github.com/dsccommunity/SqlServerDsc/blob/8dde54df19ccbdb95629ec1c074e7a97acf229d2/tests/Unit/Classes/ResourceBase.Tests.ps1#L111-L165
Also, see my answer here which contains example code: "Unable to find type" when mocking class in a Powershell unit test另外,请在此处查看我的答案,其中包含示例代码: 在 Powershell 单元测试中出现 mocking class 时“无法找到类型”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.