Pester - access original function from a Mock

Welcome Forums General PowerShell Q&A Pester - access original function from a Mock

This topic contains 1 reply, has 2 voices, and was last updated by

3 years, 2 months ago.

  • Author
  • #35478

    Topics: 1
    Replies: 0
    Points: 0
    Rank: Member

    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

    Topics: 9
    Replies: 2322
    Points: 0
    Rank: Member

    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!

The topic ‘Pester - access original function from a Mock’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort