Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unit testing 在使用Pester测试PowerShell脚本时,如何模拟文件?_Unit Testing_Powershell_Pester - Fatal编程技术网

Unit testing 在使用Pester测试PowerShell脚本时,如何模拟文件?

Unit testing 在使用Pester测试PowerShell脚本时,如何模拟文件?,unit-testing,powershell,pester,Unit Testing,Powershell,Pester,我正在尝试使用Pester测试我的PowerShell代码。我想模拟出以下行的文件: $interactiveContent | Out-File -Append -FilePath (Join-Path $destDir $interactiveOutputFile) 但我想在测试时给出自己的文件路径 我尝试了以下方法: Mock Out-File { $destDir = 'c:\snmp_poc_powershell\' $interactiveOutputFile =

我正在尝试使用Pester测试我的PowerShell代码。我想模拟出以下行的文件:

$interactiveContent | Out-File -Append -FilePath (Join-Path $destDir $interactiveOutputFile)
但我想在测试时给出自己的文件路径

我尝试了以下方法:

Mock Out-File {
    $destDir = 'c:\snmp_poc_powershell\'
    $interactiveOutputFile = 'abc.csv'  
}

但它不起作用

因此代码片段肯定是个问题,您没有返回任何值,因此模拟将为空,但是out文件实际上从未返回任何开始的内容,因此我不确定您模拟的是什么输出?除非您只是想让它假装输出到一个文件并移动到管道中的下一个阶段,您当前的代码就是这样做的(只需执行
模拟文件{}


但是,如果您希望输出到不同的路径,为什么不在为测试创建变量时使用该路径,而不用模拟呢?

这里有一种模拟
文件的方法,以便在运行测试时将其写入不同的位置:

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上提出了它。我发现您不能直接从模拟中调用正在模拟的cmdlet,但他们建议使用此解决方案,即使用
Get命令
将cmdlet放入变量,然后使用
&
来调用它,而不是cmdlet d直接的

根据另一个答案,
Out File
不会返回任何值,因此在Pester测试中,我们只需测试
$null
作为结果。您可能还希望添加后续的(集成样式)测试,您的测试文件已经创建,并且具有您期望的值。

A您的问题将真正帮助我们帮助您。