如何正确模拟我的函数以使用Pester返回自定义属性?

时间:2017-09-07 15:05:11

标签: powershell pester

我对PowerShell有点新,特别是Pester测试。我似乎无法为我正在进行Pester测试的函数重新创建一个场景。

以下是代码:

    $State = Get-Status

    if(State) {
    switch ($State.Progress) {
    0 {
       Write-Host "Session for $Name not initiated. Retrying."
      }

    100{
     Write-Host "Session for $Name at $($State.Progress) percent"
      }

    default {
     Write-Host "Session for $Name in progress (at $($State.Progress) 
    percent)."
       }
    }

我已经嘲笑Get-Status返回true,以便代码路径进入if块,但结果不具有{{1}的任何值}。

我的测试总是在代码路径方面进入默认块。我试过了 创建自定义对象$State.Progress无济于事。

以下是我的Pester测试的一部分:

$State = [PSCustomObject]@{Progress = 0}

1 个答案:

答案 0 :(得分:2)

有几个问题:

  • 根据4c的评论,您的Mock可能因为范围界定而被调用(除非您的上下文中有描述块未显示)。如果您将Context更改为Describe然后使用Assert-VerifiableMocks,则可以看到Mock随后会被调用。
  • 您无法验证使用Write-Host的代码的输出,因为此命令不会写入正常输出流(它写入主机控制台)。如果删除Write-Host以便将字符串返回到标准输出流,则代码可以正常工作。
  • 您可以使用[PSCustomObject]@{Progress = 0}按照建议模拟.Progress属性的输出,但我相信这应该在Get-Status的模拟内部。

以下是一个有效的最小/可验证示例:

$Name = 'SomeName'

#Had to define an empty function in order to be able to Mock it. You don't need to do this in your code as you have the real function.
Function Get-Status { }

#I assumed based on your code all of this code was wrapped as a Function called Confirm-Session
Function Confirm-Session  {
    $State = Get-Status

    if ($State) {
        switch ($State.Progress) {
        0 {
            "Session for $Name not initiated. Retrying."
          }

        100{
            "Session for $Name at $($State.Progress) percent"
          }

        default {
            "Session for $Name in progress (at $($State.Progress) percent)."
           }
        }
    }
}

#Pester tests for the above code:
Describe 'State Progress returns 0' {
    mock Get-Status {
        [PSCustomObject]@{Progress = 0}
    } -Verifiable

    #$State = [PSCustomObject]@{Progress = 0}

    $result = Confirm-Session

    it 'should be' {
        $result | should be "Session for $Name not initiated. Retrying."
    }

    it 'should call the verifiable mocks' {
        Assert-VerifiableMocks
    }
 }

返回:

Describing State Progress returns 0
  [+] should be 77ms
  [+] should call the verifiable mocks 7ms