如何在Pester测试中模拟Read-Host?

时间:2016-12-22 13:55:52

标签: powershell pester

如果我有这个功能:

Function Test-Foo {

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

如何模拟读取主机以返回我想要的内容?例如我想做这样的事情(这不起作用):

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

        $result = Test-Foo

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

1 个答案:

答案 0 :(得分:6)

这种行为是正确的:

你应该改变你的代码

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"
        }
    }
}
相关问题