如何让Pester 5.5.0中的Mock在脚本测试中生效?
Pester 5.5.0 Mock不生效的问题解决
是的,问题出在作用域上。你通过. $PSCommandPath.Replace(...)加载的Get-CurrentDate函数运行在全局作用域,而Pester默认在Describe块的局部作用域创建Mock,导致全局作用域的Get-Date未被Mock覆盖,函数依然调用了真实的系统时间。
解决方法
方法一:Mock全局作用域的Get-Date
修改测试脚本中的Mock语句,添加-Scope Global参数,让Mock覆盖全局作用域的Get-Date:
BeforeAll { . $PSCommandPath.Replace('.Tests.ps1', '.ps1') } Describe 'Get-CurrentDate Tests' { # 添加 -Scope Global 覆盖全局作用域的Get-Date Mock Get-Date { return [DateTime]'2023-01-01' } -Scope Global It 'returns the mocked date' { $expected = [DateTime]'2023-01-01' $actual = Get-CurrentDate $actual | Should -Be $expected } }
方法二:将函数封装为模块(推荐)
这种方式更符合PowerShell开发规范,能避免作用域污染,测试隔离性更好:
构建模块结构:
- 新建
MyModule文件夹 - 文件夹内创建
MyModule.psm1文件:function Get-CurrentDate { return Get-Date }
- 新建
修改测试脚本,导入模块并指定模块名Mock:
BeforeAll { # 强制导入模块(替换为你的模块实际路径) Import-Module -Path .\MyModule\MyModule.psm1 -Force } Describe 'Get-CurrentDate Tests' { # 指定模块名,Mock模块内调用的Get-Date Mock Get-Date { return [DateTime]'2023-01-01' } -ModuleName MyModule It 'returns the mocked date' { $expected = [DateTime]'2023-01-01' $actual = Get-CurrentDate $actual | Should -Be $expected } }
内容的提问来源于stack exchange,提问作者joe-jeff
相关产品推荐
相关产品推荐

