Pester - access original function from a Mock

Tagged: 

This topic contains 1 reply, has 2 voices, and was last updated by Profile photo of Dave Wyatt Dave Wyatt 7 months, 1 week ago.

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #35478
    Profile photo of replicaJunction
    replicaJunction
    Participant

    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!

    #35484
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    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!

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.