powershellpester

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


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

Solution

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