【问题标题】:How can I Mock Out-File when testing my PowerShell script with Pester?使用 Pester 测试我的 PowerShell 脚本时如何模拟输出文件?
【发布时间】:2017-04-24 22:26:12
【问题描述】:
我正在尝试使用 Pester 测试我的 PowerShell 代码。我想为以下行模拟out-file:
$interactiveContent | Out-File -Append -FilePath (Join-Path $destDir $interactiveOutputFile)
但我想在测试时提供自己的文件路径。
我尝试了以下方法:
Mock Out-File {
$destDir = 'c:\snmp_poc_powershell\'
$interactiveOutputFile = 'abc.csv'
}
但它不起作用。
【问题讨论】:
标签:
unit-testing
powershell
pester
【解决方案1】:
这是一种模拟 Out-File 的方法,以便在运行测试时写入不同的位置:
Describe 'Mocking out-file' {
$outFile = Get-Command Out-File
Mock Out-File {
$MockFilePath = '.\Test\Test.txt'
& $outFile -InputObject $InputObject -FilePath $MockFilePath -Append:$Append -Force:$Force -NoClobber:$NoClobber -NoNewline:$NoNewline
}
It 'Should mock out-file' {
"Test" | Out-File -FilePath Real.txt -Append | Should Be $null
}
}
这个解决方案来自 Pester 的开发人员,我在 Github 上将其作为issue 提出。我发现您不能直接从 Mock 中调用您正在模拟的 cmdlet,但他们建议使用此解决方案,您使用 Get-Command 将 cmdlet 放入变量中,然后使用 & 调用它而不是直接使用 cmdlet。
根据另一个答案,Out-File 不返回任何值,因此在 Pester 测试中,我们只需测试$null 作为结果。您可能还想添加您的测试文件已创建并具有您期望的值的后续(集成式)测试。
【解决方案2】:
所以代码 sn-p 绝对是一个问题,你没有返回任何值,所以模拟只是空的,但是 out-file 实际上从不返回任何开始的东西,所以我不确定你在模拟什么输出?除非你只是想让它假装输出到一个文件并移动到你的管道中的下一个阶段,你当前的代码就是这样做的(所以只会做Mock Out-File {}。
但是,如果您希望输出到不同的路径,为什么不在为测试创建变量时使用该路径而不用 Mock?