0

我正在使用版本纠缠版本 5.1.0

我创建了一个简单的 test.psm1

function testScript { write-host 'hello' }

我创建了一个纠缠文件让我们称之为 test-tests.ps1

Describe "test" {
    Context "test call" {
           Import-Module .\test.psm1
           Mock -ModuleName 'test' testScript { write-host 'hello3' } 
           testScript
    }
}

当我运行它时,它会返回“你好”。对于我的生活,我无法理解为什么 Pester 不会使用 testScript 的 Mock 版本并返回“hello3”。任何人都看到我在纠缠时哪里出错了?

4

1 回答 1

1

-ModuleName参数告诉Mock在哪里注入模拟,而不是在哪里找到函数定义。

您目前正在做的是说任何testScript来自模块内部的调用都test.psm1应该被拦截并替换为模拟,但是来自模块外部(例如在您test-tests.ps1testScript.

https://pester-docs.netlify.app/docs/usage/modules

请注意,在此示例测试脚本中,所有对 Mock 和 Should -Invoke 的调用都添加了 -ModuleName MyModule 参数。这告诉 Pester 将模拟注入模块的作用域,这会导致从模块内部对这些命令的任何调用都改为执行模拟。

简单的解决方法是删除-ModuleName test参数。

为了让它更清楚一点,请尝试在您的模块中添加第二个函数:

测试.psm1

function testScript
{
    write-host 'hello'
}

function testAnother
{
    testScript
}

并将您的测试套件更新为:

测试-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

取决于注入模拟的位置(即在模块内部或在测试套件内部)。

于 2021-05-21T14:41:44.180 回答