I have the following code in my Test:
It "Set mock partitions"{
Mock Get-Disk {
return [PSCustomObject]@{
SerialNumber = "SERIAL"
}
}
Mock Get-Partition {
param([PSCustomObject] $InputObject)
return @([PSCustomObject]@{
PartitionNumber = 1
},[PSCustomObject]@{
PartitionNumber = 2
})
}
Custom-Function
}
In my main script, i have the following function:
function Custom-Function(){
$Disk = Get-Disk
$Partition = Get-Partition -InputObject $Disk
}
When i run the test, i get the following error message:
The error happens on the line where Get-Partition -InputObject $Disk
is called.
Is there something wrong with my mock-definition of the InputObject
parameter, or something else i am missing?
CodePudding user response:
The error is correct in that the Get-Partition
cmdlet doesn't have an -InputObject
parameter and despite you adding one to your Mock, it isn't accessible in Pester. Pester Mocks the parameters automatically.
I managed to get a working example by using the CimInstance constructor to create the expected object that Get-Disk returns and then sending this as input to the -Disk
parameter:
Describe 'Tests' {
BeforeAll {
function Custom-Function() {
$Disk = Get-Disk
$Partition = Get-Partition -Disk $Disk
}
}
It "Set mock partitions" {
Mock Get-Disk {
$Result = [Microsoft.Management.Infrastructure.CimInstance]::new('MSFT_Disk','root/Microsoft/Windows/Storage')
$Result | Add-Member -Name SerialNumber -Value 'SERIAL' -MemberType NoteProperty
Return $Result
}
Mock Get-Partition {
return @([PSCustomObject]@{
PartitionNumber = 1
}, [PSCustomObject]@{
PartitionNumber = 2
})
}
Custom-Function
Assert-MockCalled Get-Disk
Assert-MockCalled Get-Partition
}
}
This issue was helpful: https://github.com/pester/Pester/issues/1944