问题
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