How would one go about properly mocking ‘Invoke-Command’ for this example? This is just a part of my function that I’m trying to test at the moment, the second part removes the package if there is a match (calling ‘Invoke-Command’ a second time with a different script block)…
function Remove-ChocoPackage{
param( [Parameter(Mandatory=$true)]
$packageName,
[Parameter(Mandatory=$true)]
$computerName )
$success = $false
$listPackages = @(Invoke-Command -ComputerName $computerName -ScriptBlock {choco list -lo})
$containsPackage = if(@($listPackages) -eq $packageName){$true}else{$false}
if($containsPackage){
$success = $true
}
return $success
}
The test
Describe 'Test package existence'{
$packageName1 = "Package1"
$packageName2 = "Package2"
$computerName = "comp1234"
It 'is it there'{
Mock Invoke-Command { return $packageName1,$packageName2 }
{ Remove-ChocoP -packageName $packageName1 -computerName $computerName } | Should -Be $true
Assert-MockCalled Invoke-Command -Scope It
}
}
Results in:
Expected Invoke-Command to be called at least 1 times but was called 0 times
As mentioned earlier, the full function calls ‘Invoke-Command’ a second time. I’m trying to understand how I can Mock ‘Invoke-Command’ for the two different calls, or do I need to even further and Mock ‘choco’?
The full function:
function Remove-ChocoPackage{
param(
[Parameter(Mandatory=$true)]
$packageName,
[Parameter(Mandatory=$true)]
$computerName
)
$success = $false
$listPackages = @(Invoke-Command -ComputerName $computerName -ScriptBlock {choco list -lo})
$containsPackage = if(@($listPackages) -eq $packageName){$true}else{$false}
if($containsPackage){
$removeStatus = invoke-command -ComputerName $computerName -ScriptBlock {choco uninstall $args[0] -y | out-null
if($?)
{
return $true
}
else
{
return $false
}
} -argumentList $packageName
if($removeStatus){
$success = $true
}
}
else{
$success = $true
}
return $success
}