我使用的是版本pester版本5.1.0
我已经创建了一个简单的test.psm1
function testScript { write-host 'hello' }我已经创建了一个pester文件,我们将其命名为test-tests.ps1
Describe "test" {
Context "test call" {
Import-Module .\test.psm1
Mock -ModuleName 'test' testScript { write-host 'hello3' }
testScript
}
}当我运行这个命令时,返回的结果是“hello”。我真不明白为什么佩斯特不使用模拟版的testScript并返回'hello3‘。有没有人知道我纠缠的地方在哪里?
发布于 2021-05-21 22:41:44
-ModuleName参数告诉Mock在哪里注入模拟,而不是在哪里找到函数定义。
您当前所做的是,任何从test.psm1模块内部对testScript的调用都应该被拦截并替换为模拟,但是来自模块外部(例如,在您的test-tests.ps1中)的任何调用仍然调用原始testScript。
来自https://pester-docs.netlify.app/docs/usage/modules
请注意,在此示例测试脚本中,对Mock
-Invoke的所有调用都添加了-ModuleName MyModule参数。这会告诉Pester将mock注入到模块的作用域中,这会导致模块内部对这些命令的任何调用都会执行mock。
简单的解决方法是删除-ModuleName test参数。
为了让它更清楚一些,请尝试在模块中添加第二个函数:
test.psm1
function testScript
{
write-host 'hello'
}
function testAnother
{
testScript
}并将您的测试套件更新为:
test-tests.ps1
Describe "test" {
Context "test call" {
Import-Module .\test.psm1
Mock -ModuleName 'test' testScript { write-host 'hello3' }
testScript
testAnother
}
}如果您尝试使用和不使用-ModuleName 'test',您将看到输出为
hello3
hello或
hello
hello3这取决于mock被注入的位置(即模块内部或测试套件内部)。
https://stackoverflow.com/questions/67637468
复制相似问题