Mocking New-PSSession with Pester

Hey Everyone,

Looking for a trick to mock New-PSSession. The class doesn’t have a constructor, so I can’t use New-Object or New-MockObject. Do you have any tricks for mocking this command?


I’ve played with this a lot - not sure its feasible. As you say, you can’t directly construct the resulting session object, so you can’t return a session. The only solution would be to mock whatever is using the session also, like Invoke-Command or whatever. That way you don’t need a session. You basically mock all Remoting :slight_smile:

It’s a tough one. The only valid workaround I can find is from a cached searched page where Dave Wyatt explains to mock by creating a new session to localhost.

Mock New-PSSession Using Localhost

I’ll go this route for now. If there is a better way, then this would be juicy info for the “Mocking the Unmockable” section!

In my case I am trying to mock Invoke-Command. My implementation of Invoke-Command uses a session parameter, which Invoke-Command attempts to validate. Since I can’t create a mock PSSession object, the parameter validation fails, which causes the mock of Invoke-Command to fail.

Thanks for the quick response, Don!


I’m a bit late to the party, but I think I found a workaround to this one while working on the xExchange DSC module. I had a need to be able to Mock calls to New/Remove/Import-PSSession, but as you all found, you cannot Mock them unless you pass a valid PSSession. The workaround I found for this is to define a new, empty, parameter-less New/Remove/Import-PSSession function within the Define block of the Pester tests you’re trying to Mock them in. Then Pester will successfully Mock it regardless of what objects you’re trying to pass. Here’s an example of a test where I want to Mock the Remove-PSSession function:


Describe ‘xExchangeHelper\Remove-RemoteExchangeSession’ -Tag ‘Helper’ {
function Remove-PSSession {}

AfterEach {

Context ‘When Remove-RemoteExchangeSession is called and sessions exist’ {
It ‘Should remove the sessions’ {
Mock -CommandName Get-ExistingRemoteExchangeSession -Verifiable -MockWith { return ‘SomeSession’ }
Mock -CommandName Remove-PSSession -Verifiable