我在尝试模拟 powershell 5 类方法时遇到问题,在执行测试时,出现错误“CommandNotFoundException:无法找到 Command FunctionToMock”。我试图通过模拟“FunctionToMock”来对“OutputToOverwrite”方法进行单元测试。我想我必须首先模拟 ChocoClass 本身,但我不知道该怎么做。谢谢。
Class ChocoClass
{
[string] OutputToOverwrite()
{
return $this.FunctionToMock()
}
[string] FunctionToMock()
{
return "This text will be replaced"
}
}
Describe "Testing mocking"{
it "Mock test"{
Mock FunctionToMock -MockWith {return "mystring"}
$package = New-Object ChocoClass
$expected = $package.OutputToOverwrite()
$expected | should BeExactly "mystring"
}
}
我见过两种方法可以做到这一点:
- 将大部分实现分成一个函数。
- 从类继承并重写方法。
(1) 使用函数
我一直将方法的实现分成这样的函数:
Class ChocoClass
{
[string] OutputToOverwrite()
{
return $this.FunctionToMock()
}
[string] FunctionToMock()
{
return FunctionToMock $this
}
}
function FunctionToMock
{
param($Object)
return "This text will be replaced"
}
完成此更改后,您的测试就在我的计算机上通过了。这避免了与 PowerShell 类相关的陷阱,也避免了测试类行为。
(2) 方法的派生和重写
您可以派生该类并覆盖您想要模拟的方法:
Describe "Testing mocking"{
it "Mock test"{
class Mock : ChocoClass {
[string] FunctionToMock() { return "mystring" }
}
$package = New-Object Mock
$expected = $package.OutputToOverwrite()
$expected | should BeExactly "mystring"
}
}
这个测试在我的电脑上通过了。我还没有在生产代码中使用过这种方法,但我喜欢它的直接性。请注意与在单个 PowerShell 会话中重新定义具有相同名称的类相关的问题(请参阅下面的旁注)。
旁注:(1)的分离最大限度地减少了我遇到的数量当您对类进行更改时,此错误会阻止重新加载类 https://github.com/PowerShell/PowerShell/issues/2505#issuecomment-263157383。不过,我发现更好的解决方法是在新的 PowerShell 会话中调用每个测试运行(例如PS C:\>powershell.exe -Command { Invoke-Pester }
)所以我现在倾向于(2)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)