【问题标题】:Unit Testing a Class-based DSC resource with Pester使用 Pester 对基于类的 DSC 资源进行单元测试
【发布时间】:2017-01-17 17:32:54
【问题描述】:

我在对基于类的 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
        }
    }
}

有谁知道如何做到这一点?

提前致谢

【问题讨论】:

  • 不确定资源是什么样子,但首先想到的是:InModuleScope xVMWareVM { } 围绕代码?

标签: unit-testing powershell dsc pester


【解决方案1】:

您目前无法使用 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
        }
    }
}

【讨论】:

  • 非常感谢,这正是我想要的:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-19
相关资源
最近更新 更多