我正在为一个相当复杂的脚本编写测试,脚本中有一个特定的函数可以向用户输出不同系列的日志消息。我想断言是否正在显示特定的日志消息。
主要问题是我不知道什么参数隐式处理我传递Write-Host
cmdlet的文本。
这是一些代码,它们捕捉了我正在尝试做的事情的前提......
function TestFunction($TestInput) {
if ($TestInput -contains 1) {
Write-Host "TestInput contains a 1"
}
if ($TestInput -contains 3 ) {
Write-Host "TestInput contains a 3"
}
if ($TestInput -contains 4 ) {
Write-Host "TestInput contains a 4"
}
}
Run Code Online (Sandbox Code Playgroud)
Describe "TestFunction" {
It "should call Write-Host with appropriate message if 1 or 3 is passed" {
Mock Write-Host {}
TestFunction -TestInput @(1, 2, 3)
Assert-MockCalled Write-Host -Exactly 2 -Scope It
Assert-MockCalled Write-Host -Exactly 1 -Scope It -ParameterFilter { "TestInput contains a 1" }
Assert-MockCalled Write-Host -Exactly 1 -Scope It -ParameterFilter { "TestInput contains a 3" }
}
}
Run Code Online (Sandbox Code Playgroud)
Describing TestFunction
[-] should call Write-Host with appropriate message if 1 or 3 is passed 19ms
at <ScriptBlock>, : line 235
235: Assert-MockCalled Write-Host -Exactly 1 -Scope It -ParameterFilter { "TestInput contains a 1" }
Expected Write-Host to be called 1 times exactly but was called 2 times
Tests completed in 106ms
Tests Passed: 0, Failed: 1, Skipped: 0, Pending: 0, Inconclusive: 0
Run Code Online (Sandbox Code Playgroud)
在查看了cmdlet的Microsoft 文档Write-Host
后,我发现有一个-Object
参数。这接受要写入控制台的通用对象数组。该-Object
参数是需要在被指定的参数-ParameterFilter
的纠缠测试以断言正在显示适当的文本。
我更新的代码如下...
function TestFunction($TestInput) {
if ($TestInput -contains 1) {
Write-Host "TestInput contains a 1"
}
if ($TestInput -contains 3 ) {
Write-Host "TestInput contains a 3"
}
if ($TestInput -contains 4 ) {
Write-Host "TestInput contains a 4"
}
}
Run Code Online (Sandbox Code Playgroud)
Describe "TestFunction" {
It "should call Write-Host with appropriate message if 1 or 3 is passed" {
Mock Write-Host {}
TestFunction -TestInput @(1, 2, 3)
Assert-MockCalled Write-Host -Exactly 2 -Scope It
Assert-MockCalled Write-Host -Exactly 1 -Scope It -ParameterFilter { $Object -eq "TestInput contains a 1" }
Assert-MockCalled Write-Host -Exactly 1 -Scope It -ParameterFilter { $Object -eq "TestInput contains a 3" }
}
}
Run Code Online (Sandbox Code Playgroud)
Describing TestFunction
[+] should call Write-Host with appropriate message if 1 or 3 is passed 20ms
Tests completed in 99ms
Tests Passed: 1, Failed: 0, Skipped: 0, Pending: 0, Inconclusive: 0
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1435 次 |
最近记录: |