[英]How to setup a Pester mock with arguments from a function
我有一个 PowerShell 函数,不幸的是它有几个依赖项,所以在测试时我需要设置几个不同的模拟。 由于我有几个不同场景的测试,其中一些但并非全部共享类似的设置活动,因此测试之间最终会出现大量重复。 我想通过将SetupValidStateForUser
的声明移动到辅助函数中来减少测试中的重复,例如SetupValidStateForUser
我可以毫无问题地从函数中声明 Mocks,但是一旦我引入了一个使用-ParameterFilter
的 Mock,该 Mock 使用来自辅助函数的参数,看起来当 Mocks 是时,我的辅助函数的传入参数不在范围内解决。 如何调整模拟声明以便正确解析我的参数?
我在 PowerShell 7 中使用 Pester v5。
这是一个显示失败场景的测试:
Context "Setting up a Mock from a Function" {
BeforeEach {
Function SubjectUnderTest {
Param(
[string]$Arg1
)
return $true
}
Function Setup-MockForSubjectUnderTest {
Param(
[string] $ExpectedArg,
[bool] $ReturnValue
)
Mock SubjectUnderTest `
-Verifiable `
-ParameterFilter { $Arg1 -eq $ExpectedArg } ` # <-- scope issue?
-MockWith { $ReturnValue }
}
}
It "Should allow me to setup a mock with parameters from a helper function" {
# arrange
Setup-MockForSubjectUnderTest -ExpectedArg "hello" -ReturnValue $true
# act
$result = SubjectUnderTest -Arg1 "hello"
# assert
$result | Should -Be $true
Should -InvokeVerifiable # <-- fails
}
}
是的,这是一个范围问题,因此您可以在可访问的范围内创建变量,如下所示:
Describe "Test" {
Context "Setting up a Mock from a Function" {
BeforeEach {
Function SubjectUnderTest
{
Param(
[string]$Arg1
)
return $false
}
Function Setup-MockForSubjectUnderTest
{
Param(
[string] $ExpectedArg,
[bool] $ReturnValue
)
New-Variable -Name "mockExpectedArg" -Value $ExpectedArg -Scope "script" -Force
New-Variable -Name "mockReturnValue" -Value $ReturnValue -Scope "script" -Force
Mock SubjectUnderTest `
-Verifiable `
-ParameterFilter { $Arg1 -eq $mockExpectedArg } `
-MockWith { return $mockReturnValue }
}
}
It "Should allow me to setup a mock with parameters from a helper function" {
# arrange
Setup-MockForSubjectUnderTest -ExpectedArg "hello" -ReturnValue $true
# act
$result = SubjectUnderTest -Arg1 "hello"
# assert
$result | Should -BeTrue
Should -InvokeVerifiable
}
It "Should allow me to setup a mock with parameters from a helper function" {
# arrange
Setup-MockForSubjectUnderTest -ExpectedArg "bye" -ReturnValue $false
# act
$result = SubjectUnderTest -Arg1 "bye"
# assert
$result | Should -BeFalse
Should -InvokeVerifiable
}
}
}
但也尝试使用TestCases
(有关更多信息,请参阅 Pester 文档),例如:
It "Given valid -Name '<Filter>', it returns '<Expected>'" -TestCases @(
@{ Filter = 'Earth'; Expected = 'Earth' }
@{ Filter = 'ne*' ; Expected = 'Neptune' }
) {
param ($Filter, $Expected)
$planets = Get-Planet -Name $Filter
$planets.Name | Should -Be $Expected
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.