构建测试用例所需的任何东西都需要放在一个BeforeDiscovery { ... }
块中。中的代码BeforeAll { ... }
被推迟到执行测试之前,但是您的哈希表需要比发现之前$expected
更早可用,以便从您的测试用例构建每个测试。除此之外,您需要将块嵌套在 a或块中It { ... }
Describe
Context
更新:根据您的评论 - 为了在$Expected
不复制 BeforeEach 块中的分配的情况下使测试范围可用,您可以将变量的范围设置为脚本范围
BeforeDiscovery {
$script:Expected = @{
Address1 = 'Value_Address1'
Address2 = 'Value_Address2'
City = 'Value_City'
RegionCode = 'Value_RegionCode'
PostalCode = 'Value_PostalCode'
}
}
Describe "Need a describe or context block" {
BeforeEach {
Mock Invoke-SqlCmd
Invoke-MyFunction @Expected
}
It "sets the column '<Name>' with the value '<Value>'" -TestCases (
$Expected.GetEnumerator() |
ForEach-Object { @{Name = $_.Key; Value = $_.Value } }
) {
# param($Name, $Value)
$Test = "*{0}='{1}'*" -f $Name, $Value
# Assert-MockCalled Invoke-Sqlcmd -ParameterFilter {
# $Query -like $Test
# }
}
}
输出
Pester v5.3.1
Starting discovery in 1 files.
Discovery found 5 tests in 25ms.
Running tests.
Running tests from 'C:\temp\powershell\pester.tests.ps1'
Describing Need a describe or context block
[+] sets the column 'RegionCode' with the value 'Value_RegionCode' 8ms (4ms|4ms)
[+] sets the column 'City' with the value 'Value_City' 2ms (1ms|1ms)
[+] sets the column 'Address2' with the value 'Value_Address2' 5ms (1ms|3ms)
[+] sets the column 'PostalCode' with the value 'Value_PostalCode' 3ms (1ms|2ms)
[+] sets the column 'Address1' with the value 'Value_Address1' 3ms (1ms|2ms)
Tests completed in 168ms
Tests Passed: 5, Failed: 0, Skipped: 0 NotRun: 0
请参阅 Pester 的 v5 Discovery and Run文档
从该页面解释:
这是在初始发现阶段运行 Invoke-Pester 时发生的情况
- 调用测试脚本文件
BeforeAll
函数运行仅保存提供给它的脚本块,不执行它(尚未)此块中的哈希表和其他变量尚未创建
Describe
函数运行并调用提供给它的脚本块,以收集有关其中包含的测试的信息。注意:Describe
和Context
scriptblocks 是在发现期间运行的唯一脚本块
-TestCases
提供给It
函数的所有参数(包括)都由 PowerShell 评估(这是需要哈希表的地方,但遗憾的是它还没有出现)
It
-TestCases
函数运行保存(不运行)包含生成测试的代码,先前评估的数组中的每个项目 1
Write-Host "Discovery done."
正在运行。