Ala*_*n T 2 powershell unit-testing pester
我正在使用Pester对我编写的某些代码进行单元测试。在测试中,我Test-Path使用参数过滤器进行了模拟:
Mock -CommandName 'Test-Path' -MockWith { return $false } `
-ParameterFilter { $LiteralPath -and $LiteralPath -eq 'c:\dummy.txt' }
Run Code Online (Sandbox Code Playgroud)
以下是我正在做的伪代码:
If ( Test-Path -LiteralPath c:\dummy.txt )
{
return "Exists"
}
else
{
Attempt to get file
If ( Test-Path -LiteralPath c:\dummy.txt )
{
return "File obtained"
}
}
Run Code Online (Sandbox Code Playgroud)
在第一次通话中Test-Path我想返回$false,在第二个通话中我想返回$true。我可以想到几种实现此目的的方法,但是它们感觉不正确:
第一次调用时使用Path参数,第二次使用LiteralPath。有两个模拟ParameterFilter,每个模拟一个。我不喜欢为了方便测试而修改代码的想法。
创建具有以下参数的函数:Path和InstanceNumber。为该函数创建模拟。这比上面的要好,但是我不喜欢仅用于测试目的的参数的想法。
我已经看过,但找不到基于第n个调用进行模拟的方法。佩斯特(Pester)对此有帮助吗,我刚刚错过了吗?如果没有,有没有一种更清洁的方式来实现我想要的?
function Test-File{
If ( Test-Path -LiteralPath c:\dummy.txt )
{
return "Exists"
}
else
{
If ( Test-Path -LiteralPath c:\dummy.txt )
{
return "File obtained"
}
}
}
Describe "testing files" {
it "file existence test" {
#Arrange
$script:mockCalled = 0
$mockTestPath = {
$script:mockCalled++
if($script:mockCalled -eq 1)
{
return $false
}
else
{
return $true
}
}
Mock -CommandName Test-Path -MockWith $mockTestPath
#Act
$callResult = Test-File
#Assert
$script:mockCalled | Should Be 2
$callResult | Should Be "File obtained"
Assert-MockCalled Test-Path -Times $script:mockCalled -ParameterFilter { $LiteralPath -and $LiteralPath -eq 'c:\dummy.txt' }
}
}
Run Code Online (Sandbox Code Playgroud)
我想你在追吗?让我知道是否!
| 归档时间: |
|
| 查看次数: |
734 次 |
| 最近记录: |