Pester PSSession Mocking

After having run afoul of trying to do this and finding the below thread as the top Google result, I wanted to correct some information that is no longer accurate in the original (locked) thread.

Original thread: https://powershell.org/forums/topic/mocking-new-pssession-with-pester/

Core of the problem: When using Pester to Mock Import-PSSession or other functions that take a PSSession object from New-PSSession, the functions that consume the PSSession do validation on their (required) Session parameter that will cause even the mocked function to fail if they’re not passed an actual PSSession object.

As of the time of the original post, there weren’t any known ways to mock the PSSession object. However, as of today (and assuming Pester 4.4.3+ and PowerShell 5.1+ or PowerShell Core), you can create a mock PSSession object as follows:

[pre]

Mock New-PSSession { return New-MockObject System.Management.Automation.Runspaces.PSSession }

[/pre]

Hopefully this can help someone else that’s stumbling through the issue via Google searches.

This is a general forum.

You should write this in the Pester forum.

Anyway, thanks for the tip!