Given my powershell code (not in a function, as the last few parts are the script running, but i want to check some stuff for my script, using pester) My powershell code WinVersion.ps1
$WindowsVersion = Get-CimInstance -ClassName Win32_Operatingsystem | select -expand Caption
My Pester script:
BeforeAll {
. $PSCommandPath.Replace('.Tests.ps1', '.ps1')
}
Describe "Test Server 2012" {
It "Given Server 2012, return correct data" {
Mock -CommandName Get-CimInstance -ParameterFilter {$ClassName -eq "Win32_Operatingsystem"} -MockWith {
Write-Host "CIM"
return [Microsoft.Management.Infrastructure.CimInstanc]@{
Caption = "Microsoft Windows Server 2012 Datacenter"
}
}
write-host $WindowsVersion
}
}
My Write-host (in my pester script) should return Microsoft Windows Server 2012 Datacenter
but it returns my own windows version. It thus ignores my mock.
I also tried the mock without the ParameterFilter, but that also didn't work.
This is the result that Pester gives me:
Starting discovery in 1 files.
Discovery found 2 tests in 82ms.
Running tests.
[-] Test Server 2012.Given Server 2012, return correct data 46ms (45ms|1ms)
Expected strings to be the same, but they were different.
Expected length: 40
Actual length: 31
Strings differ at index 18.
Expected: 'Microsoft Windows Server 2012 Datacenter'
But was: 'Microsoft Windows 11 Enterprise'
------------------^
at $WindowsVersion | Should -Be "Microsoft Windows Server 2012 Datacenter"
Any clue why?