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



我正在尝试使用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
}
}

噗。测试.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'}
}

你的代码对我来说似乎很好用。我使用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

最新更新