3

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"
        }
    }
}
Pete Whitehead
  • 178
  • 2
  • 11

2 Answers2

7

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"
        }
    }
}
Bert Levrau
  • 975
  • 8
  • 11
  • When i run it it still hangs on the Read-Host line though? `PS D:\Temp\Scrap> invoke-pester Describing Test-Foo Context When something Tell me a file path:` – Pete Whitehead Jan 05 '17 at 10:00
  • I have changed the example, Can you please try to coppy this to a new ps1 and test if you have the desired result? – Bert Levrau Jan 05 '17 at 10:31
  • That does work! In my test I have the function I want to test in a separate psm1 file. I must be importing it wrong. Thanks a lot! – Pete Whitehead Jan 05 '17 at 11:15
  • 1
    This example does not currently work for me in Pester v5 – Zam Aug 12 '21 at 19:56
  • The `Mock` statement is contextual on Pester v5. You can move the `Mock` statement into `BeforeAll {}` section within the `Describe {}` section, or into the same `It {}` section where you use `Read-Host`. – zionyx Sep 16 '21 at 13:04
0

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
        }
    }
}
zionyx
  • 1,927
  • 19
  • 14