Search code examples
powershellpowershell-5.0pester

Pester Mock of Get-Date not called when using -ParameterFilter


I have created a new Pester fixture and am trying to mock a call to the Get-Date CmdLet, but it is not working. It does work if I don't use -ParameterFilter.

dummy.ps1

function dummy {
    return Get-Date -f "dd"
}

dummy.Tests.ps1

$here = Split-Path -Parent $MyInvocation.MyCommand.Path
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests\.', '.'
. "$here\$sut"

Describe "dummy" {
    Mock Get-Date { return "01" } -Verifiable -ParameterFilter {$f -match "dd"}

    It "does something useful" {
        dummy

        Assert-VerifiableMocks 
    }
}

Output

Describing dummy
 [-] does something useful 99ms
   RuntimeException:  Expected Get-Date to be called with $f -match "dd"
   at Assert-VerifiableMocks, C:\Program Files\WindowsPowerShell\Modules\Pester\3.4.0\Functions\Mock.ps1: line 434
   at <ScriptBlock>, E:\…\dummy.Tests.ps1: line 11
Tests completed in 99ms
Passed: 0 Failed: 1 Skipped: 0 Pending: 0 Inconclusive: 0

I've tried using -eq instead of -match for the -ParameterFilter with no difference.

I feel like I must be doing something wrong at a very basic level, but can't see it - can anybody help me?

If it makes any difference this is on a Windows 10 virtual machine; the output from $PSVersionTable is:

Name                           Value                                                                                        
----                           -----                                                                                        
PSVersion                      5.1.14393.1198                                                                               
PSEdition                      Desktop                                                                                      
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}                                                                      
BuildVersion                   10.0.14393.1198                                                                              
CLRVersion                     4.0.30319.42000                                                                              
WSManStackVersion              3.0                                                                                          
PSRemotingProtocolVersion      2.3                                                                                          
SerializationVersion           1.1.0.1

Solution

  • This issue occurs because you're using $f to represent the -format parameter. -f is a commonly used short-hand for -format (and what you're using in your Function), but seemingly for the Mock to work you need to use full parameter names:

    Mock Get-Date { return "01" } -Verifiable -ParameterFilter {$format -match "dd"}
    

    Returns:

    Describing dummy
     [+] does something useful 31ms