我使用一个简单的类编写了以下 MyTypes 模块:
class Person {
[string] $Name
Person([string] $name ) {
$this.Name = $name
}
}
然后我定义了以下 MyModule 模块来使用它:
using module "C:\temp\StackOverflow\PSModules\MyTypes\MyTypes.psm1"
Import-Module "C:\temp\StackOverflow\PSModules\MyTypes\MyTypes.psm1" -Force
function MyFunction {
param (
[Parameter(Mandatory = $true)]
[Person] $person
)
Write-Output "Hello $($person.Name)"
}
# Export the function
Export-ModuleMember -Function MyFunction
最后写了一个 Pester 测试,但失败了,因为它似乎无法利用对 MyTypes 模块中类定义的引用
using module "C:\temp\StackOverflow\PSModules\MyTypes\MyTypes.psm1"
BeforeAll {
Import-Module "C:\temp\StackOverflow\PSModules\MyTypes\MyTypes.psm1" -Force
Import-Module "C:\temp\StackOverflow\PSModules\MyModule\MyModule.psm1" -Force
}
Describe 'MyFunction' {
Mock Write-Output {}
$person = [Person]::new("John Doe")
It 'should call my function' {
MyFunction -Person $person
Assert-MockCalled -CommandName Write-Output -Exactly 1 -Scope It
}
}
运行 Pester 测试时,我收到错误“无法将参数绑定到参数‘person’,因为它为空”。在我的实际代码中,我实际上收到错误,即 Pester 无法解析类型。我想使用 MyTypes 之类的模块来保持类在我的代码中的组织和引用,这对实际代码来说很好,但给我的 Pester 测试不合适。有人对这个问题或解决方案有见解吗?
我正在运行 Pester 5.7.1 和 PowerShell 7.5.0
与Pester Mock PowerShell 类函数中的命令中描述的问题非常相似,您在您的和您的语句
-ModuleName
中都缺少了。此外,语句应该在块内。在此示例中应与实际模块名称相对应。Mock
Assert-MockCalled
Mock
BeforeAll
MyModule
与链接答案中建议的相同,使用
InModuleScope
另一个选项,它不需要您-ModuleName
在模拟调用中添加参数: