Here is a way to Mock Out-File
such that it writes to a different location when running testing:
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
}
}
This solution came from the developers of Pester after I raised this as an issue on Github. I had found that you can't directly call the cmdlet you are mocking from within the Mock, but they advised this solution where you use Get-Command
to put the cmdlet in to a variable and then use &
to invoke it instead of the cmdlet directly.
Per the other answer, Out-File
doesn't return any value, so in the Pester test we simply test for $null
as the result. You would probably also want to add subsequent (integration-style) tests that you test file had been created and had the values you expect.