Pester模拟中的空列表是从闭包创建的

时间:2016-01-27 23:48:20

标签: powershell pester

为什么以下代码:

  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)

导致错误:

  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

作为参考,跟踪输出给出:

WWWWW=>System.Collections.Generic.List`1[System.String]
XXXXX=>C:\dummy\command.exe -S "blah" -d "blahblah" -i "something.sql"
YYYYY=>

当我使用以下内容时,它可以工作:

  $dummyMock = (CreateExecutedCommandsLogger $executedCommands)
  &$dummyMock "blah"

我假设这与执行模拟中的脚本块的方式有关?

1 个答案:

答案 0 :(得分:0)

从源(Get-Command Mock).ScriptBlock可以看出,有一行使用$MockWith参数:

$mockWithCopy = [scriptblock]::Create($MockWith.ToString())

这样,$MockWith实际上是一个字符串,忽略了任何闭包。可能它已完成,因为在下一行新创建的脚本块$mockWithCopy受限于某个会话状态,因此您无论如何都会松开关闭:

Set-ScriptBlockScope -ScriptBlock $mockWithCopy -SessionState $contextInfo.Session

Pester首先执行脚本块的私有副本,以不影响传递的实例。