我有一些旧的 Pester v4 测试,当我尝试在 Pester v5 中运行它们时,它们失败了。
在 Pester v4 中,我读到一旦Mock
被调用,它将继续应用于Describe
块的其余部分,即使它是在It
块内调用的。Describe
因此,我会在块之外的块中调用它It
,以表明它不仅仅适用于单个It
块。
在 Pester v4 中有效的行为似乎在 Pester v5 中不起作用。
这是我正在编写测试的脚本 MyScriptToTest.ps1:
function Get-FirstText ()
{
return 'Some text'
}
function Get-SecondText ()
{
return 'Other text'
}
function Get-Text ()
{
$a = Get-FirstText
$b = Get-SecondText
return "$a; $b"
}
以下是 MyScriptToTest.Tests.ps1 中的测试:
BeforeAll {
. (Join-Path $PSScriptRoot 'MyScriptToTest.ps1')
}
Describe 'Get-FirstText' {
It 'returns text "Some text"' {
$result = Get-FirstText
$result | Should -Be 'Some text'
}
}
Describe 'Get-Text' {
It 'returns text "Some text; Other text"' {
Get-Text | Should -Be 'Some text; Other text'
}
Mock Get-FirstText { return 'Mock text' }
It 'returns text "Mock text; Other text" after mocking Get-FirstText' {
Get-Text | Should -Be 'Mock text; Other text'
}
}
Pester v5测试输出如下:
Describing Get-FirstText
[+] returns text "Some text" when called indirectly 13ms (8ms|5ms)
Describing Get-Text
[+] returns text "Some text; Other text" 66ms (54ms|13ms)
[-] returns text "Mock text; Other text" after mocking Get-FirstText 42ms (41ms|1ms)
Expected strings to be the same, but they were different.
String lengths are both 21.
Strings differ at index 0.
Expected: 'Mock text; Other text'
But was: 'Some text; Other text'
^
at Get-Text | Should -Be 'Mock text; Other text', C:\...\MyScriptToTest.Tests.ps1:20
at <ScriptBlock>, C:\...\MyScriptToTest.Tests.ps1:20
Tests completed in 565ms
Tests Passed: 2, Failed: 1, Skipped: 0 NotRun: 0
但是,如果我将Mock
命令移到块中It
,那么它就会起作用:
BeforeAll {
. (Join-Path $PSScriptRoot 'MyScriptToTest.ps1')
}
Describe 'Get-FirstText' {
It 'returns text "Some text"' {
$result = Get-FirstText
$result | Should -Be 'Some text'
}
}
Describe 'Get-Text' {
It 'returns text "Some text; Other text"' {
Get-Text | Should -Be 'Some text; Other text'
}
It 'returns text "Mock text; Other text" after mocking Get-FirstText' {
Mock Get-FirstText { return 'Mock text' }
Get-Text | Should -Be 'Mock text; Other text'
}
}
我还没有弄清楚Mock
在 Pester v5 中调用命令的新限制。是否仍可以在块内、块外Mock
调用该命令?或者现在总是必须在块内调用它?Describe
Context
It
It
文档
Mock
描述了 v5+ 对命令必须(现在)放置位置的更改(添加了重点):也就是说,直接
Mock
放置在一个或多个命令内部的命令(如您问题中的代码中所示)现在实际上被忽略了。Describe
Context
详细说明:在Pester v5+中,为了使
Mock
语句有效,必须将其放置在以下构造之一内:BeforeAll
在命令内部,因此适用于同一范围内的所有测试。BeforeAll
可以直接放置在Describe
命令内,或者 - 为了更细粒度的控制 - 放置在嵌套Context
命令内。在单个
It
命令内,在这种情况下它仅适用于该测试。在您的代码上下文中,这意味着:
Context
-级别Mock
:It
-级别Mock
: