我在单元测试一个基于类的DSC资源时遇到了问题。我试图Mock类中的几个函数,但我得到了一个强制转换错误。
PSInvalidCastException: Cannot convert the "bool TestVMExists(string vmPath,
string vmName)" value of type "System.Management.Automation.PSMethod" to type
"System.Management.Automation.ScriptBlock".我的测试代码是:
using module 'C:\Program Files\WindowsPowerShell\Modules\xVMWareVM\xVMWareVM.psm1'
$resource = [xVMWareVM]::new()
Describe "Set" {
Context "If the VM does not exist" {
Mock xVMWareVM $resource.TestVMExists {return $false}
Mock xVMWareVM $resource.CreateVM
It "Calls Create VM once" {
Assert-MockCalled $resource.CreateVM -Times 1
}
}
}有谁知道如何做到这一点吗?
提前感谢
发布于 2017-01-18 06:25:29
你目前还不能使用Pester模拟一个类函数。当前的解决方法是使用Add-Member -MemberType ScriptMethod替换该函数。这意味着您将不会得到模拟断言。
这是我借给DockerDsc tests by @bgelens的。
没有你的类代码,我无法测试这一点,但它应该给你的想法,以及上述的@bgelens代码。
using module 'C:\Program Files\WindowsPowerShell\Modules\xVMWareVM\xVMWareVM.psm1'
Describe "Set" {
Context "If the VM does not exist" {
$resource = [xVMWareVM]::new()
$global:CreateVmCalled = 0
$resource = $resource |
Add-Member -MemberType ScriptMethod -Name TestVMExists -Value {
return $false
} -Force -PassThru
$resource = $resource |
Add-Member -MemberType ScriptMethod -Name CreateVM -Value {
$global:CreateVmCalled ++
} -Force -PassThru
It "Calls Create VM once" {
$global:CreateVmCalled | should be 1
}
}
}https://stackoverflow.com/questions/41703468
复制相似问题