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

て烟熏妆下的殇ゞ 提交于 2019-12-11 03:49:26

问题


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:


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"
        }
    }
}


来源:https://stackoverflow.com/questions/41284810/how-do-i-mock-read-host-in-a-pester-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!