Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking class functions with Pester 5 and PowerShell 7

Does anyone have an example of mocking a dot-sourced class function with Pester 5 and PowerShell 7?

Thank you.

Edit: example

Classes\MyClass.ps1:

class MyClass {
    [void] Run() {
        Write-Host "Class: Invoking run..."
    }
}

MyModule.psm1:

# Import classes
. '.\Classes\MyClass.ps1'

# Instantiate classes
$MyClass = [MyClass]::new()

# Call class function
$MyClass.Run()
like image 733
XeonFibre Avatar asked Oct 16 '25 12:10

XeonFibre


1 Answers

Pester only mocks commands - not classes or their methods.

The easiest way to "mock" a PowerShell class for method dispatch testing is by taking advantage of the fact that PowerShell marks all methods virtual, thereby allowing derived classes to override them:

class MockedClass : MyClass
{
  Run() { Write-host "Invoking mocked Run()"}
}

The nice thing about this approach is that functions that constrain input to the MyClass type will still work with the mocked type:

function Invoke-Run
{
  param([MyClass]$Instance)

  $instance.Run()
}

$mocked = [MockedClass]::new()
Invoke-Run -Instance $mocked    # this still works because [MockedClass] derives from [MyClass]
like image 149
Mathias R. Jessen Avatar answered Oct 18 '25 06:10

Mathias R. Jessen