I am creating a module which contains a class file as well as a unit test file (Pester).
The class B
in the class file inherits from a class A
found in another module.
If I try to run a unit test that mocks class B
by inheriting it, I get "Unable to find type [B]"
However, If I simply instantiate class B
, everything works.
Why can't I inherit from the class, when I am able to instantiate it?
Unit test file:
using module ".\MyModule.psd1"
BeforeAll {
Import-Module $PSScriptRoot\MyModule.psd1 -Force
}
Describe 'My unit test 1' {
It 'Runs unit test 1' {
# Mock a private function
# Gives: Unable to find type [B].
class MockedClassB : B
{
MockedClassB ([int]$foo) : base($foo)
{
}
[string] MyMethod() { return 'MockedString' }
}
$mockedB = [MockedClassB]::new(13)
$mockedB.Run()
}
}
Describe 'My unit test 2' {
It 'Runs unit test 2' {
# No errors.
$instanceB = [B]::new(13)
$instanceB.Run()
}
}
MyModule.psd1:
@{
RootModule = 'Include.psm1'
ModuleVersion = '1.0.0'
# This is needed to use classes. Otherwise the Test file will give "Unable to find type"
ScriptsToProcess = @(
'Classes\B.ps1'
)
RequiredModules = ''
# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export.
FunctionsToExport = @()
# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export.
CmdletsToExport = @()
# Variables to export from this module
# VariablesToExport = '*'
# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export.
AliasesToExport = @()
}
Include.psm1:
#Requires -Version 5.0
[cmdletbinding()]
param()
Write-Verbose $PSScriptRoot
Write-Verbose 'Import Classes in order because of dependencies'
$classList = @(
'B'
)
foreach($class in $classList)
{
Write-Verbose " Class: $class"
. "$psscriptroot\Classes\$class.ps1"
}
B.ps1:
using module ".\..\..\ModuleContainingClassA\ModuleContainingClassA.psd1"
class B: A
{
# ctor
B([int]$foo)
{
}
}
[EDIT] If I replace the dot-including of the classes in the module file Include.psm1, and instead just let it contain the class definition(s), the error disappears.
I also found a similar question here, without any accepted answer: Mocking class functions with Pester 5 and PowerShell 7