我对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}
答案 0 :(得分:2)
有几个问题:
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