Search code examples
unit-testingpowershellmockingcode-coveragepester

How do I prevent Pester Mocked Read-Host from prompting for input during Code Coverage


I have a Pester test where I mock up a Read-Host call for my function, which follows the format in this question here:

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

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

My tests run perfectly when using this format, and calling the test directly. However, when I run the file that contains my test using Invoke-Pester "MyTestFile" -CodeCoverage "MyFileUnderTest", I am being prompted to enter a Read-Host value for my test.

My intent is that the test will run automatically without having to enter a Read-Host value. This would be both when calling the test directly (which works currently), and when calling my test file with the CodeCoverage command.

Does anyone know of a way to achieve this?

Edit:

To the first comment I received, I have reviewed Pester's documentation, including this link https://github.com/pester/Pester/wiki/Unit-Testing-within-Modules. I haven't seen any official documentation from Pester regarding using Read-Host however, and used the solution I found in the StackOverflow link at the top of my question.

Source Code for Module Test-Foo function:

function Test-Foo
{
    return (Read-Host "Enter value->");
}

Solution

  • Given your use-case: Module Test-Foo function

    function Test-Foo {
        return (Read-Host -Prompt 'Enter value->')
    }
    

    I would advise you to instead mock the Test-Foo function:

    Context 'MyModule' {
        Mock -ModuleName MyModule Test-Foo { return 'C:\example' }
    
        It 'gets user input' {
            Test-Foo | Should -Be 'C:\example'
        }
    }