I'm a bit new to PowerShell and specifically Pester testing. I can't seem to recreate a scenario for the function I am making Pester test.
Here is the code:
$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)."
}
}
I've mocked Get-Status
to return true so that the code path would go inside the if
block, but then the result doesn't have any value for $State.Progress
.
My test would always go into the default block in terms of code path. I tried
creating a custom object $State = [PSCustomObject]@{Progress = 0}
to no avail.
Here is part of my Pester test:
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."
}
}
There are a couple of issues:
Context
toDescribe
and then useAssert-VerifiableMocks
you can see that the Mock does then get called.Write-Host
because this command doesn't write to the normal output stream (it writes to the host console). If you removeWrite-Host
so that the strings are returned to the standard output stream, the code works.[PSCustomObject]@{Progress = 0}
to mock the output of a.Progress
property as you suggested, but I believe this should be inside the Mock ofGet-Status
.Here's a minimal/verifiable example that works:
Returns: