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

1k Views Asked by At

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

There are 2 best solutions below

5
On BEST ANSWER

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

An extension to Bert's answer, this is the updated code sample for Pester v5.

The difference from Pester v4 is that Mocks are scoped based on their placement.

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