【问题标题】:Can't Pass Pester Test because of local variable variable error由于局部变量变量错误,无法通过 Pester 测试
【发布时间】:2018-01-11 06:27:50
【问题描述】:

我很难使用调用命令为特定的 Powershell 函数创建纠缠器,并且在脚本块上有一个 $using 变量。每当我运行我的测试时,它总是会返回一个错误。示例功能和测试如下:

功能:

Function Execute-Function {
.
.
.
$Name = "Computer_Name"

$ScriptBlock = {
    Import-Module "Activedirectory"
    Get-Computer -Name $Using:Name
}

Invoke-Command -Session $Session -ScriptBlock $ScriptBlock
}

测试:

Describe 'Execute-Function' {
.
.
.
.
mock Import-Module {} -verifiable

mock Get-Computer {} -verifiable

mock Invoke-Command {
 param($Scriptblock)
 . $Scriptblock
} -verifiable


$result = Execute-Function

it 'should call all verifiable mocks'{
 Assert-verifiablemocks
}
}

我的测试错误将返回 无法检索使用变量。 using 变量只能与 Invoke-Command 一起使用.... 即使我模拟了 Get-Computer 以不返回任何内容,我也无法理解此错误?还是我需要更改模拟 Get-Computer 的方式才能通过测试?

提前致谢

【问题讨论】:

  • 一种潜在的解决方法是使用旧方法在脚本块中包含一个参数块,通过参数列表将参数传递给 Invoke-Command。
  • 嗨@TheIncorrigible1 感谢您的回复。这是否意味着我必须编辑函数本身?抱歉,我还没有足够的知识。
  • 是的,它需要重写任何对Invoke-Command 的调用才能使用参数块。 Invoke-Command { param($myparam) ... } -ArgumentList ...
  • 哇,感谢@TheIncorrigible1,我的测试现在通过了,而且我可以实现 100% 的代码覆盖率。你真的帮了我很多。非常感谢。
  • 太好了,我会把它作为答案发布。

标签: unit-testing powershell pester


【解决方案1】:

我不确定您是否可以使用 Pester 模拟 $using: 范围。但是,您可以使用 pre-$using:-scope 的处理方式:

Invoke-Command -ScriptBlock {
    Param(
        [Parameter(Position = 0)]
        [String] $Name
    )

    <# ... #>

} -ArgumentList $Name

【讨论】:

  • 这按预期工作,目前是我们的最佳解决方案。我已经尝试以编程方式解决此问题以避免更改生产代码的需要,但是没有成功我在这里记录了我在一个问题中的尝试:github.com/pester/Pester/issues/2015
猜你喜欢
  • 1970-01-01
  • 2013-03-12
  • 2022-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-17
  • 2020-07-30
相关资源
最近更新 更多