简体   繁体   English

从关闭创建的Pester Mock中的空列表

[英]Null List in Pester Mock created from a closure

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: 从源代码(Get-Command Mock).ScriptBlock可以看到,在一行中使用$MockWith参数:

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

So that, $MockWith effectively is a string and any closure ignored. 因此, $MockWith实际上是一个字符串,任何闭包都将被忽略。 Likely it is done because on next line newly created script block $mockWithCopy bounded to some session state, thus you loose your closure anyway: 之所以可能这样做是因为在下一行中,新创建的脚本块$mockWithCopy绑定到某个会话状态,因此无论如何您都会松开闭包:

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

Pester first do private copy of script block to not affect passed instance. Pester首先执行脚本块的私有副本,以不影响传递的实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM