[英]How can Pester mock the “test” function in the pattern “test existence (not found) - create - test again to confirm creation”?
这是一些伪代码,显示要测试的功能:
function Set-Something
{
if (Test-Something)
{
return $True
}
# Not found so do something to create it.
Do-Something
# Check it's been created successfully.
if (Test-Something)
{
return $True
}
return $False
}
这必须是一个相当普遍的模式:“测试是否存在-如果找不到,请创建-再次测试以验证创建”。 测试大多数分支非常简单,但是如何在第一次调用Test-Something失败然后第二次调用成功的地方测试分支呢?
到目前为止,这是我的测试代码:
Describe 'Set-Something' {
Context 'already exists' {
Mock Test-Something { return $True }
Mock Do-Something
It 'returns True' {
{ Set-Something } | Should -Be $True
}
It 'does not call Do-Something' {
Set-Something
Assert-MockCalled Do-Something -Times 0 -Exactly
}
}
Context 'does not already exist and creation fails' {
Mock Test-Something { return $False }
Mock Do-Something
It 'calls Do-Something' {
Set-Something
Assert-MockCalled Do-Something -Times 1 -Exactly
}
It 'calls Test-Something twice' {
Set-Something
Assert-MockCalled Test-Something -Times 2 -Exactly
}
It 'returns False' {
{ Set-Something } | Should -Be $False
}
}
Context 'does not already exist and creation succeeds' {
Mock Test-Something { ?? }
Mock Do-Something
It 'calls Do-Something' {
Set-Something
Assert-MockCalled Do-Something -Times 1 -Exactly
}
It 'calls Test-Something twice' {
Set-Something
Assert-MockCalled Test-Something -Times 2 -Exactly
}
It 'returns True' {
{ Set-Something } | Should -Be $True
}
}
}
问题是“尚不存在,创建成功”。 需要对Test-Something进行模拟,以便它在第一次调用时失败,而在第二次调用时成功。 传递给Test-Something的参数在每个调用中将是相同的,因此我不能使用ParameterFilter创建具有不同行为的Test-Something的两个模拟。
我发现了两种模拟方法:
1)使用“静态”(即脚本作用域)变量记录状态
Context 'does not already exist and creation succeeds' {
BeforeEach {
$script:exists = $False
}
AfterAll {
Remove-Variable exists -Scope Script
}
Mock Test-Something {
return $script:exists
}
Mock Do-Something {
$script:exists = $True
}
It 'calls Do-Something' {
Set-Something
Assert-MockCalled Do-Something -Times 1 -Exactly
}
It 'calls Test-Something twice' {
Set-Something
Assert-MockCalled Test-Something -Times 2 -Exactly
}
It 'returns True' {
{ Set-Something } | Should -Be $True
}
}
2)使用哈希表记录状态
Context 'does not already exist and creation succeeds' {
BeforeEach {
$mockState = @{
ItExists = $False
}
}
Mock Test-Something {
return $mockState.ItExists
}
Mock Do-Something {
$mockState.ItExists = $True
}
It 'calls Do-Something' {
Set-Something
Assert-MockCalled Do-Something -Times 1 -Exactly
}
It 'calls Test-Something twice' {
Set-Something
Assert-MockCalled Test-Something -Times 2 -Exactly
}
It 'returns True' {
{ Set-Something } | Should -Be $True
}
}
我个人喜欢哈希表,因为$mockState. ...
$mockState. ...
在我看来似乎比$script:...
更能说明变量的用途。 同样,如果测试并行化并且另一个Describe块修改了相同的变量,则脚本范围的变量可能会导致竞争。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.