Pester 5.1.0 对已导入模块函数执行Mock未生效问题求助
问题原因分析
- 你给
Mock加了-ModuleName 'test'参数,这个参数的作用是将Mock的作用范围限定在test.psm1模块的内部调用场景,只有模块内部的代码调用testScript时才会走你定义的Mock逻辑。你当前直接在测试脚本作用域调用testScript,调用的是导入到测试作用域的原始函数,自然不会触发Mock。 - 额外不规范点:Pester 5 不推荐直接在
Context/Describe块下直接执行导入模块、Mock这类初始化操作,建议统一放到BeforeAll/BeforeEach块中,避免作用域异常。
对应解决方案
场景1:你需要Mock测试脚本作用域调用的testScript
直接去掉-ModuleName 'test'参数即可,修正后的测试代码如下:
Describe "test" { BeforeAll { Import-Module .\test.psm1 -Force Mock testScript { write-host 'hello3' } } Context "test call" { testScript } }
运行后输出就是hello3。
场景2:你需要Mocktest.psm1模块内部调用的testScript
首先需要修改模块,增加一个内部调用testScript的外层函数,示例模块代码:
function testScript { write-host 'hello' } function Invoke-Test { # 模块内部调用testScript testScript } Export-ModuleMember -Function Invoke-Test, testScript
此时测试代码保留-ModuleName 'test'参数,调用模块暴露的外层函数即可触发Mock:
Describe "test" { BeforeAll { Import-Module .\test.psm1 -Force Mock -ModuleName 'test' testScript { write-host 'hello3' } } Context "test module internal call" { Invoke-Test } }
运行后输出为hello3。
内容的提问来源于stack exchange,提问作者orange-lily
相关产品推荐
相关产品推荐

