I have a PowerShell function that unfortunately has several dependencies, so when testing I need to setup several different mocks. As I have several tests with different scenarios and some but not all share similar setup activities, there ends up being a lot of duplication between the tests. I want to reduce duplication in my tests by moving the declaration of the mocks into helper functions, eg SetupValidStateForUser
I can declare Mocks from functions without issues, but as soon as I introduce a Mock that uses a -ParameterFilter
that uses an argument from the helper function it looks like the passed-in parameters to my helper functions are not in scope when the Mocks are resolved. How can I adjust the mock declaration so that my arguments will be resolved correctly?
I'm using Pester v5 with PowerShell 7.
Here's a test that shows the failing scenario:
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
}
}