Trouble Mocking Set-ADuser

I am running into some issues trying to mock Set-ADUser. The ‘Sync-OTLUserWithAD’ function contains Get-ADuser and Set-ADuser calls but it will not respect the Set-ADuser mock and instead loads the ActiveDirectory Module and I either get InvalidCastException or insufficient rights errors when I run my pester tests. Any ideas?

Describe “Sync-OTLWithADUser” {
It “Syncs information correctly” {
Mock -CommandName Get-ADUser -MockWith {Return (Import-Clixml .\Test_AD_User.xml)}
Mock -CommandName Set-ADUser -MockWith {$Instance | Export-Clixml -Path .\After_Set.xml}
$OTLUser = Get-OTLUser “EmployeeNumber”
Sync-OTLUserWithAD -OTLUser $OTLUser
$BeforeTest = (Import-Clixml .\Test_AD_User.xml)
$AfterTest = (Import-Clixml -Path .\After_Set.xml)
$Props = $ | Select -ExpandProperty Name
(Compare-Object -ReferenceObject $Before -DifferenceObject $After -Property $Props).count | Should be 0
} # end it

} # end describe

Your mocks look good. When you mock a command, it will still load the module. It has to do this to read the command’s parameters and other things.

When you get an invalid cast exception that makes me think that Sync-OTLUserWithAD’s OTLUser parameter is an explicit type. Ensure that $OTLUser is the correct object type by running Sync-OTLUserWithAD for real and piping it to Get-Member. Once you get that object type, then you can use New-MockObject -Type ‘whatever’ for your mock.

Thanks for the reply! I ended up coming to the conclusion that if it was this hard to write a test my function was probably just doing to much. Everything looks good since I split it up a bit and removed Set-ADUser from the equation.