Author Posts

February 19, 2016 at 11:40 am

I'm working on a Pester test for a log rotation function. One of the things I'd like to be able to do is mock Get-Date with a few different dates (yesterday, a week ago, etc.) to create test files and make sure my function rotates the logs correctly.

My problem is that I also rely heavily on Get-Date -Format 'yyyyMMdd-hhmm' (and a couple of other format Strings) for formatting dates in a couple of different ways for use in a filename and in a log entry.

Is it possible to reference the original Get-Date function from within a mock of Get-Date?

So far, I'm doing some trickery with ParameterFilters, but for some reason, it's providing double output.

            $dateToday = Get-Date
            $dateYesterday = $dateToday.AddDays(-1)
            Mock Get-Date -ParameterFilter {$Date -eq $null} {
                Write-Host "Mock Get-Date: format=$Format";
                Get-Date -Date $dateYesterday -Format $Format # should write output
            }
            
            Get-Date | write-host -fore green

This is giving me close to what I'd expect, but with double output somehow:

Mock Get-Date: format=
2/18/2016 1:06:39 PM
2/18/2016 1:06:39 PM

Where is the second output coming from? Is there another method I can use to mock Get-Date and still access the original Get-Date?

Thanks in advance!

February 19, 2016 at 12:28 pm

Personally, I'd just do something like this:

$getDateCmdlet = Get-Command -Name Get-Date -CommandType Cmdlet
Mock Get-Date {
    Write-Host "Mock Get-Date: format=$Format";
    & $getDateCmdlet -Date $dateYesterday -Format $Format # should write output
}

That said, I think you've just pointed me at a bug in Pester. If you call a mock from inside itself, there's some weird stuff happening (even if it falls through to the original command). Thanks!