Hi All,
I have been struggling a long time because of my pester not reaching 100% code coverage due to a scriptblock. I have been researching and reading articles to no success and I have decided to ask some help from you guys. :)
Part of the code I want to describe contains a scriptblock and would later be fed to a cmdlet Invoke-Command. Sample code below:
function Get-Function {
.....
Set-Alias Start-PowerShell32 $env:computername\WindowsPowerShell\v1.0\powershell.exe"
$ScriptBlock = {
Start-PowerShell32 -noprofile {
$sample = Get-Content -Path "C:\sample.txt
Import-Module "C:\Program Files (x86)\Software"
@($sample) | Get-Service | Where-Object { $_.Status -eq 'Stopped' }
}
}
Invoke-Command -ScriptBlock $ScriptBlock
}
Describe Get-Function {
....
function Get-Statistics {
Start-PowerShell32 -noprofile {
$sample = Get-Content -Path "C:\sample.txt
Import-Module "C:\Program Files (x86)\Software"
@($sample) | Get-Service | Where-Object { $_.Status -eq 'Stopped' }
}
}
Context '1st Context'{
mock Set-Alias {'Setting alias for Powershell 32 bit'} -Verifiable
mock Get-Statistics {'Getting Statistics ....'} -Verifiable
mock Invoke-Command {Get-Statistics} -Verifiable
$result = Get-Function
it 'should return etting alias for Powershell 32 bit'{
$result[0] | should be "Setting alias for Powershell 32 bit"
}
it 'should return Getting Mailbox Statistics ....'{
$result[1] | should be "Getting Statistics ...."
}
it 'should call all verifiable mocks'{
Assert-VerifiableMocks
}
}
}
What I did on my Pester is that I made a custom function inside my Describe block(Get-Statistics) which is basically the inside of the script block for it to be called whenever I mock Invoke-Command to be Get-Statistics. My Pester succeeds but code coverage does not give me 100%. Can you guys enlighten me on how to do this? do I need to change my tests? Thank You
At the head of your Describe {
block, include a mock for Invoke-Command
:
Describe '..' {
Mock Invoke-Command { Param($SB) . $SB }
...
}