2

我对 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块内,但是结果对于$State.Progress.

就代码路径而言,我的测试总是会进入默认块。我尝试创建自定义对象$State = [PSCustomObject]@{Progress = 0}无济于事。

这是我的 Pester 测试的一部分:

    Context 'State Progress returns 0' {
    mock Get-Status {return $true} -Verifiable
    $State = [PSCustomObject]@{Progress = 0}
    $result =  Confirm-Session 
       it 'should be' {
           $result | should be "Session for $Name not initiated. Retrying."
        }
    }
4

1 回答 1

2

有几个问题:

  • 根据 4c 的评论,您的 Mock 可能由于范围限制而未被调用(除非您的上下文周围有一个 describe 块未显示)。如果您更改ContextDescribe然后使用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
于 2017-09-07T15:34:11.563 回答