【发布时间】: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