如何在 Pester 测试中模拟 Read-Host?
How do I mock Read-Host in a Pester test?
如果我有这个功能:
Function Test-Foo {
$filePath = Read-Host "Tell me a file path"
}
如何将 Read-Host 模拟成我想要的 return?例如我想做这样的事情(这是行不通的):
Describe "Test-Foo" {
Context "When something" {
Mock Read-Host {return "c:\example"}
$result = Test-Foo
It "Returns correct result" {
$result | Should Be "c:\example"
}
}
}
这种行为是正确的:
您应该将代码更改为
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"
}
}
}
的扩展,这是 Pester v5 的更新代码示例。
与 Pester v4 的区别在于 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
}
}
}
如果我有这个功能:
Function Test-Foo {
$filePath = Read-Host "Tell me a file path"
}
如何将 Read-Host 模拟成我想要的 return?例如我想做这样的事情(这是行不通的):
Describe "Test-Foo" {
Context "When something" {
Mock Read-Host {return "c:\example"}
$result = Test-Foo
It "Returns correct result" {
$result | Should Be "c:\example"
}
}
}
这种行为是正确的:
您应该将代码更改为
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"
}
}
}
与 Pester v4 的区别在于 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
}
}
}