2

I am trying to test my PowerShell code using Pester. I want to mock out-file for the following line:

$interactiveContent | Out-File -Append -FilePath (Join-Path $destDir $interactiveOutputFile)

But I want to give my own file path while testing.

I have tried the following:

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

but it is not working.

Mark Wragg
  • 22,105
  • 7
  • 39
  • 68
  • A [minimum complete and verifiable example](http://stackoverflow.com/help/mcve) of your problem would really help us to help you. – alx9r Nov 06 '16 at 01:10

2 Answers2

4

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.

Mark Wragg
  • 22,105
  • 7
  • 39
  • 68
0

So the code snippet is definitely a problem, your not returning any values so the mock will just be empty, however out-file never actually returns anything to begin with so I'm not exactly sure what output you are mocking? unless you just want it to pretend to output to a file and move to the next stage in your pipeline, which your current code does(so would just doing Mock Out-File {}.

However if you are looking to output to a different path why not just use that path when you create the variables for your test and not bother with a Mock?

Mike Garuccio
  • 2,588
  • 1
  • 11
  • 20