How do I mock Read-Host in a Pester test?

2019-07-20 07:12发布

If i have this function:

Function Test-Foo {

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

How do i mock the Read-Host to return what i want? e.g. I want to do something like this (which doesn't work):

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条回答
三岁会撩人
2楼-- · 2019-07-20 07:41

This behavior is correct:

you should change you're code to

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"
        }
    }
}
查看更多
登录 后发表回答