gpt4 book ai didi

powershell - 将 PowerShell 散列的键/值与 Pester 测试用例一起使用

转载 作者:行者123 更新时间:2023-12-04 14:47:35 27 4
gpt4 key购买 nike

我想通过 TestCases 参数将 PowerShell 哈希的键/值传递给 Pester 单元测试:

BeforeAll {
$Expected = @{
Address1='Address1'
Address2='Address2'
City='City'
RegionCode='RegionCode'
PostalCode='PostalCode'
}
}

BeforeEach {
Mock Invoke-SqlCmd
Invoke-MyFunction @Expected
}

It "sets the column '<Name>' with the value '<Value>'" -TestCases ( $Optional.GetEnumerator() | ForEach-Object { @{Name=$_.Key; Value=$_.Value} } ) {
param($Name, $Value)

$Test = "*{0}='{1}'*" -f $Name, $Value

Assert-MockCalled Invoke-Sqlcmd -ParameterFilter {
$Query -like $Test
}

}

但似乎无法正确“调整”散列的属性以使测试正常工作。

最佳答案

构建测试用例所需的任何内容都需要放在 BeforeDiscovery { ... } block 中。 BeforeAll { ... } 中的代码被推迟到执行测试时,但是您的 $expected 哈希表需要早于 before 发现以便从您的测试用例构建每个测试。除此之外,您需要将 It { ... } block 嵌套在 DescribeContext block 中

更新:根据您的评论 - 为了使 $Expected 可用于测试范围而不复制 BeforeEach block 中的分配,您可以将变量的范围设置为脚本范围

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 函数仅运行保存提供给它的脚本 block ,而不是执行它(还)尚未创建此 block 内的哈希表和其他变量
  • Describe 函数运行并调用提供给它的脚本 block ,以收集有关其中包含的测试的信息。注意:DescribeContext 脚本 block 是唯一在发现期间运行的脚本 block
  • 提供给 It 函数的所有参数(包括 -TestCases)由 PowerShell 评估(这是需要哈希表的地方,但遗憾的是它还没有出现)
  • It 函数运行保存(不运行)包含生成测试的代码,之前评估的 -TestCases 数组中的每个项目 1
  • Write-Host“Discovery done.”运行

关于powershell - 将 PowerShell 散列的键/值与 Pester 测试用例一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69731244/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com