Why does the following code:
function CreateExecutedCommandsLogger(){
param(
[System.Collections.Generic.List[System.String]]$cmdLog
)
"WWWWW=>{0}" -f $cmdLog | Write-Host
return{
param(
[parameter(valuefrompipeline)]$command
)
"XXXXX=>{0}" -f $command | Write-Host
"YYYYY=>{0}" -f $cmdLog | Write-Host
$cmdLog.Add($command)
}.GetNewClosure()
}
$executedCommands = New-Object System.Collections.Generic.List[System.String]
Mock ExecuteSqlCommand (CreateExecutedCommandsLogger $executedCommands)
Result in the error:
RuntimeException: You cannot call a method on a null-valued expression.
at <ScriptBlock>, <No file>: line 7
at <ScriptBlock>, C:\Users\notme\Documents\WindowsPowerShell\Modules\Pester\Functions\Mock.ps1: line 1018
at ExecuteBlock, C:\Users\notme\Documents\WindowsPowerShell\Modules\Pester\Functions\Mock.ps1: line 1022
at Invoke-Mock, C:\Users\notme\Documents\WindowsPowerShell\Modules\Pester\Functions\Mock.ps1: line 868
at <ScriptBlock><Process>, <No file>: line 53
For reference the tracing output gives:
WWWWW=>System.Collections.Generic.List`1[System.String]
XXXXX=>C:\dummy\command.exe -S "blah" -d "blahblah" -i "something.sql"
YYYYY=>
When I use the following, it works:
$dummyMock = (CreateExecutedCommandsLogger $executedCommands)
&$dummyMock "blah"
I'm assuming this is something to do with the way the script block in the mock is executed?
As you can see from source (Get-Command Mock).ScriptBlock
, there is single line where $MockWith
parameter is used:
$mockWithCopy = [scriptblock]::Create($MockWith.ToString())
So that, $MockWith
effectively is a string and any closure ignored. Likely it is done because on next line newly created script block $mockWithCopy
bounded to some session state, thus you loose your closure anyway:
Set-ScriptBlockScope -ScriptBlock $mockWithCopy -SessionState $contextInfo.Session
Pester first do private copy of script block to not affect passed instance.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.