【发布时间】:2022-08-04 06:00:06
【问题描述】:
我们试图弄清楚如何使用 Pester 从另一个脚本模拟 PSCustomObject 的 ScriptMethod。
脚本1.ps1
$script2 = & $Script2PS1Path -programName $myScriptName
function Invoke-MyFunction {
$script2.outHost(\"test data\")
Get-ChildItem -Directory -Path $path -Filter \"ABC_*\"
...
...
}
脚本2.ps1
param (
[Parameter(Mandatory=$True,ValueFromPipeline=$False,HelpMessage=\"Mandatory.\")]
[string]$programName
)
$ErrorActionPreference = \"Stop\"
$obj = New-Object PSCustomObject
$obj | Add-Member -MemberType NoteProperty -name prog -Value $programName
$obj | Add-Member -MemberType ScriptMethod -name outHost -Value {
param (
[Parameter(Mandatory=$True,ValueFromPipeline=$True)]
$text,
[Parameter(Mandatory=$False,ValueFromPipeline=$True)]
[string]$foregroundcolor,
[Parameter(Mandatory=$False,ValueFromPipeline=$True)]
[string]$backgroundcolor
)
if ($foregroundcolor -and $backgroundcolor) {
Write-Host -Foregroundcolor $foregroundcolor -Backgroundcolor $backgroundcolor $text
} elseif ($foregroundcolor) {
Write-Host -Foregroundcolor $foregroundcolor $text
} elseif ($backgroundcolor) {
Write-Host -Backgroundcolor $backgroundcolor $text
} else {
Write-Host $text
}
}
$obj
exit(0)
在上面的例子中,我们需要模拟$script2.outHost 来测试Invoke-MyFunction。模拟 $script2.outHost 的最佳方法是什么?
-
Add-Member -Force -MemberType ScriptMethod -name outHost -Value { }允许您覆盖现有的脚本方法。 -
outHost 在哪里必须被覆盖?是从测试开始的吗?有没有办法使用 pester 来模拟 $script2 及其方法?
-
Pester 只能模拟命令。例如。你可以模拟
Write-Host。这应该适用于outHost方法。在一般情况下,您可能必须将方法调用包装到 cmdlet 中,以使它们可模拟。
标签: powershell automated-tests pester