[英]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.