I am using Pester testing library (with version 5.0.2) to test my PowerShell scripts (with version 5.1) and mock its dependencies.
Pester has a Mock
method which can be used to mock dependencies. More info here.
I am trying to create a helper method wrapping this Mock method, to make my code more readable:
Function MockVstsInput {
Param(
[Parameter(Mandatory=$true, Position=1)]
[string]$inputName,
[Parameter(Mandatory=$true, Position=2)]
[string]$returnValue
)
Mock Get-VstsInput {return $returnValue} -ParameterFilter { $Name -eq $inputName}
}
In this helper method I am mocking the dependency Get-VstsInput
which has a parameter $Name
Then I use this code in my test script:
MockVstsInput "targetapi" "api-name"
Meaning that if the Get-VstsInput
is called with $Name
param "targetapi" then it should return "api-name". Usually such parameterizing works in other languages (f.e.: C# or Java), but here the $inputName
string is not resolved in the MockVstsInput method.
When I call the Get-VstsInput
method in my production code:
$newapi=Get-VstsInput -Name targetapi
Then in the log I have the following Mock information:
Mock: Running mock filter { $Name -eq $inputName } with context: Name = targetapi.
Mock: Mock filter did not pass.
Where we can see that the $inputName
string is not resolved in my scriptblock, so the mocking does not happen.
What I have tried so far, with no success:
swapping the members of the equal comparison in the predicate scriptblock
{ $inputName -eq $Name}
using
$ExecutionContext.InvokeCommand.ExpandString($inputName)
in the script block to resolve$inputName
stringcreating a script block with
[ScriptBlock]::create($Name -eq $inputName)
then using this in the-ParameterFilter
last but not least I tried to call
GetNewClosure
of my script block, but it did not help either:{ $Name -eq $inputName}.GetNewClosure()
What do you think what the root cause of my problem is? Thanks in advance for all the help!