Unit testing 使用Pester对基于类的DSC资源进行单元测试

Unit testing 使用Pester对基于类的DSC资源进行单元测试,unit-testing,powershell,dsc,pester,Unit Testing,Powershell,Dsc,Pester,我对基于类的DSC资源进行单元测试时遇到问题。我试图在类中模拟几个函数,但我得到了一个强制转换错误 PSInvalidCastException: Cannot convert the "bool TestVMExists(string vmPath, string vmName)" value of type "System.Management.Automation.PSMethod" to type "System.Management.Automation.ScriptBloc

我对基于类的DSC资源进行单元测试时遇到问题。我试图在类中模拟几个函数,但我得到了一个强制转换错误

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
        }
    }
}
有人知道如何做到这一点吗


提前感谢

您目前无法使用Pester模拟类函数。当前的解决方法是使用
addmember-MemberType ScriptMethod
替换函数。这意味着您将无法获得模拟断言

我借这个给你

如果没有您的类代码,我无法测试这个,但是它应该会让您了解上面的@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
        }
    }
}

不确定资源是什么样子,但第一个想法是:
InModuleScope xVMWareVM{}
围绕代码?非常感谢,这正是我想要的:)