Powershell模拟具有匹配参数的模块返回null

时间:2018-10-06 18:03:43

标签: powershell mocking pester

我正在尝试使用Powershell在模块中模拟Join-Path。该模拟将返回一个TestDrive位置,但我一直得到$ null而不是TestDrive位置。在我的示例模块中,$ OutputPath返回null。我的嘲笑我怎么了?

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\'}

}

1 个答案:

答案 0 :(得分:0)

您的代码对我来说似乎很好。我使用了Write-Host来检查函数中$ OutputPath值是什么,以查看将其设置为TestDrive路径。我还使用Assert-MockCalled来验证您的Mock是否被调用:

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
    }
}

您的代码根据设计返回$null