Mocking class functions with Pester 5 and PowerShell 7

帅比萌擦擦* 提交于 2021-02-19 07:37:42

问题


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()

回答1:


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]


来源:https://stackoverflow.com/questions/65200650/mocking-class-functions-with-pester-5-and-powershell-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!