3

如果我有这个功能:

Function Test-Foo {

    $filePath = Read-Host "Tell me a file path"
}

我如何模拟 Read-Host 以返回我想要的?例如,我想做这样的事情(这是行不通的):

Describe "Test-Foo" {
  Context "When something" {
        Mock Read-Host {return "c:\example"}

        $result = Test-Foo

        It "Returns correct result" {
            $result | Should Be "c:\example"
        }
    }
}
4

2 回答 2

7

这种行为是正确的:

你应该改变你的代码

Import-Module -Name "c:\LocationOfModules\Pester"

Function Test-Foo {
    $filePath = Read-Host "Tell me a file path"
    $filePath
}

Describe "Test-Foo" {
  Context "When something" {
        Mock Read-Host {return "c:\example"}

        $result = Test-Foo

        It "Returns correct result" { # should work
            $result | Should Be "c:\example"
        }
         It "Returns correct result" { # should not work
            $result | Should Be "SomeThingWrong"
        }
    }
}
于 2016-12-22T14:33:11.187 回答
0

Bert 答案的扩展,这是 Pester v5 的更新代码示例。

与 Pester v4 的不同之处在于Mocks 的范围是基于它们的位置

Function Test-Foo {
    $filePath = Read-Host "Tell me a file path"
    $filePath
}

Describe "Test-Foo" {

    BeforeAll {
        # Variables placed here is accessible by all Context sections.
        $returnText = "c:\example"
    }

    Context "When something" {

        BeforeAll {
            # You can mock here so every It gets to use this mock
            Mock Read-Host {return $returnText}
        }

        It "Returns correct result" {
            # Place mock codes here for the current It context
            # Mock Read-Host {return $returnText}

            $result = Test-Foo
            $result | Should Be $returnText
        }
    }
}
于 2021-09-16T13:14:11.130 回答