Pester Testing .Net with PowerShell Classes
One problem I’ve come across with Pester is it has no good way to Mock .Net objects. This hasn’t caused me too much trouble as I can just wrap .Net methods in functions and mock the function, but I had a case come up where I needed to specify the .Net type in my function parameter, so I couldn’t just wrap this in a function:
Function New-BadNetFunction { Param ( [Parameter(Mandatory=$true)] [Breaks.Pester.MyType]$MyType ) returns $Bad }
As you can see, I’m specifying the type and it is a required parameter, so how do I get around this? I could just use [Object] as the type, but that seems wrong. I know classes now exist in PowerShell 5, so I looked into creating a Breaks.Pester.MyType class, but that isn’t possible with PowerShell 5 classes. I could use PowerShell 5 classes to create MyType, so is there a way to get rid of Breaks.Pester?
It’d be a short blog post if there wasn’t! PowerShell 5 brought with it the idea of namespaces. You can stick these at the beginning of your code to simplify .net names. So if I just stick this at the start of my script (literally has to be line 1 and 2):
#requires -Version 5.0 using namespace Breaks.Pester
I can now simplify my function to:
Function New-GoodNetFunction { Param ( [Parameter(Mandatory=$true)] [MyType]$MyType ) returns $Good }
And now I can simply create a class in Pester and test this function with this test:
Class MyType { $Name } Describe 'CanTest' { It 'ActuallyTests!' { $Test = New-Object MyType New-GoodNetFunction -MyType $Test } }
Leave a Comment