1

I'm attempting to use Powershell to mock Join-Path with in a module. This mock will return a TestDrive location but I keep getting $null instead of the TestDrive location. In my example module $OutputPath returns with null. What am I doing wrong with my Mock?

foo.psm1

function foobar {
    $OutputPath = Join-Path -Path $PSScriptRoot -ChildPath '..\..\..\Output\'
    if (!(test-path $OutputPath) ) {
        $null = New-Item -ItemType directory -Path $OutputPath
    }
}

foo.Tests.ps1

import-module foo.psm1
Describe "Mock Example" {
    $TestLocation = New-Item -Path "TestDrive:\Output\" -ItemType Directory

    Mock -CommandName 'Join-Path' -MockWith { return $TestLocation.FullName } -ModuleName 'Foo' -ParameterFilter {$ChildPath -eq '..\..\..\Output\'}

}
Maximilian Burszley
  • 18,243
  • 4
  • 34
  • 63
Eric
  • 53
  • 3

1 Answers1

0

Your code seems to work fine to me. I used a Write-Host to check what the $OutputPath value was when in the function to see it was being set to the TestDrive path. I also used Assert-MockCalled to verify your Mock was being invoked:

function foobar {
    $OutputPath = Join-Path -Path $PSScriptRoot -ChildPath '..\..\..\Output\'
    Write-Host $OutputPath

    if (!(test-path $OutputPath) ) {
        $null = New-Item -ItemType directory -Path $OutputPath
    }
}

Describe "Mock Example" {
    $TestLocation = New-Item -Path "TestDrive:\Output\" -ItemType Directory

    Mock -CommandName 'Join-Path' -MockWith { $TestLocation } -ParameterFilter {$ChildPath -eq '..\..\..\Output\'}

    It 'Should work' {
        foobar | should -be $null
        Assert-MockCalled Join-Path
    }
}

Your code returns $null by design.

Mark Wragg
  • 22,105
  • 7
  • 39
  • 68
  • To ensure that my variable is passing through to the scriptblock should I use $Using:TestLocation? – Eric Oct 08 '18 at 01:33
  • No that’s not necessary, there isn’t a scoping issue as the write-host proves the variable is getting populated. What version of Pester are you using? – Mark Wragg Oct 08 '18 at 05:35