Mock Fails Inside Function
I am attempting to mock a call to Get-WmiObject using the following code:
Mock -CommandName Get-WmiObject
-MockWith { return ([PSCustomObject]@{ Domain='domain.com'; Name='Server01' }) }
-ParameterFilter { $Class -eq 'Win32_ComputerSystem' }
We call Invoke-Pester, which then calls the .Tests.ps1 script, which then calls the function.
When inside the function scope, Get-WmiObject -Class Win32_ComputerSystem returns as if it were not mocked. Once back in the .Tests.ps1 script, however, the cmdlet is mocked correctly and returns the expected object.
Any ideas as to what is causing this?
Would have to see your test code to know for certain, but it sounds like you're calling the mocked command from a function inside a script module. There are some quirks with PowerShell scopes in that scenario, and we've got a page about it on the wiki: https://github.com/pester/Pester/wiki/Unit-Testing-within-Modules
Long story short: If the call to the mocked function is coming from within a script module, you need either InModuleScope or the -ModuleName parameter on Mock and Assert-MockCalled to make it work. (I prefer InModuleScope, personally.)
Found out this was because -ModuleName is the name of the module that is calling the mocked command, not the module in which the command resides.
Thanks!