首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Powershell Mock带有匹配参数的模块返回null

Powershell Mock带有匹配参数的模块返回null
EN

Stack Overflow用户
提问于 2018-10-07 02:03:43
回答 1查看 189关注 0票数 1

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

foo.psm1

代码语言:javascript
复制
function foobar {
    $OutputPath = Join-Path -Path $PSScriptRoot -ChildPath '..\..\..\Output\'
    if (!(test-path $OutputPath) ) {
        $null = New-Item -ItemType directory -Path $OutputPath
    }
}

foo.Tests.ps1

代码语言:javascript
复制
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\'}

}
EN

回答 1

Stack Overflow用户

发布于 2018-10-07 17:01:55

在我看来,您的代码运行得很好。当函数中的$OutputPath值被设置为TestDrive路径时,我使用了一个Write-Host来检查它的值是什么。我还使用了Assert-MockCalled来验证你的模拟正在被调用:

代码语言:javascript
复制
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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52681908

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档