我有一个 Pester 测试,我在其中为我的函数模拟了一个 Read-Host 调用,它遵循这里问题中的格式:
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"
}
}
}
当使用这种格式并直接调用测试时,我的测试运行完美。但是,当我使用 Invoke-Pester "MyTestFile"-CodeCoverage "MyFileUnderTest"运行包含我的测试的文件时,系统提示我为我的测试输入一个读取主机值。
我的意图是测试将自动运行,而无需输入 Read-Host 值。这将在直接调用测试(当前有效)和使用 CodeCoverage 命令调用我的测试文件时发生。
有谁知道实现这个的方法吗?
编辑:
对于我收到的第一条评论,我已经查看了 Pester 的文档,包括此链接 https://github.com/pester/Pester/wiki/Unit-Testing-within-Modules .但是,我还没有从 Pester 看到任何关于使用 Read-Host 的官方文档,并使用了我在问题顶部的 StackOverflow 链接中找到的解决方案。
模块 Test-Foo 函数的源代码:
function Test-Foo
{
return (Read-Host "Enter value->");
}
最佳答案
给定您的用例:
function Test-Foo {
return (Read-Host -Prompt 'Enter value->')
}
我建议您改为模拟 Test-Foo
函数:
Context 'MyModule' {
Mock -ModuleName MyModule Test-Foo { return 'C:\example' }
It 'gets user input' {
Test-Foo | Should -Be 'C:\example'
}
}
关于unit-testing - 如何防止 Pester Mocked Read-Host 在代码覆盖期间提示输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50297499/