3

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()
XeonFibre
  • 33
  • 3

2 Answers2

2

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]
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
  • How are you letting Pester know what MyClass is? `class MockedClass : MyClass`. Right now Pester is returning `Unable to find type [MyClass]`. – XeonFibre Dec 08 '20 at 14:48
  • @XeonFibre either add a `using module ModuleContainingClassDef` directive to the test script file, or define the class inline with `Invoke-Expression` (ie. `iex 'class MockedClass : ...'`) – Mathias R. Jessen Dec 08 '20 at 14:50
  • Any chance you'd know how to use Mock ... -Verifiable with your solution? Then I could ensure the mocked method is called. – XeonFibre Dec 08 '20 at 15:05
  • I didn't have much luck but it's alright, I'm going to create some interfaces and go that route instead. It'll enable me to validate the functions are being called correctly and the tests should be shorter. – XeonFibre Dec 08 '20 at 15:40
0

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

You can look at this repo: https://github.com/dsccommunity/SqlServerDsc/blob/8dde54df19ccbdb95629ec1c074e7a97acf229d2/tests/Unit/Classes/ResourceBase.Tests.ps1#L111-L165

Also, see my answer here which contains example code: "Unable to find type" when mocking class in a Powershell unit test

Rye bread
  • 1,305
  • 2
  • 13
  • 36