gpt4 book ai didi

arrays - 如何在 Pester 中将两个数组与自定义对象进行比较

转载 作者:行者123 更新时间:2023-12-03 00:33:54 28 4
gpt4 key购买 nike

我们正在努力让 Pester 测试失败或通过,这取决于 array 中的 objects 是否相等。

测试.ps1

#require Assert
#require Pester

$Expected = @(
[PSCustomObject]@{Name1 = 'Text1';Name2 = 'Text2'}
[PSCustomObject]@{Name1 = 'Text1';Name2 = 'Text2'}
)
$Actual = @(
[PSCustomObject]@{Name1 = 'Text1';Name2 = 'Text2'}
[PSCustomObject]@{Name1 = 'Text1';Name2 = 'Text2'}
)

Describe 'comparing arrays' {
Context 'Assert-Equivalent' {
it 'should be green' {
Assert-Equivalent -Actual $Expected -Expected $Expected
}
it 'should be green' {
Assert-Equivalent -Actual $Actual -Expected $Expected
}
it 'should be red' {
$Wrong = @(
[PSCustomObject]@{Name1 = 'Text1';Name2 = 'Text2'}
[PSCustomObject]@{Name1 = 'WROMG';Name2 = 'Text2'}
)
Assert-Equivalent -Actual $Wrong -Expected $Expected
}
}
Context 'Should be' {
it 'should be green' {
$Expected | Should -Be $Expected
}
it 'should be green' {
$Actual | Should -Be $Expected
}
it 'should be red' {
$Wrong = @(
[PSCustomObject]@{Name1 = 'Text1';Name2 = 'Text2'}
[PSCustomObject]@{Name1 = 'WROMG';Name2 = 'Text2'}
)
$Wrong | Should -Be $Expected
}
}
}

我们似乎无法做到这一点。我们是否使用了错误的 CmdLets?或者还有另一种检查方法吗?有时 array 也只是另一个对象的属性。因此需要进行深入比较。

最佳答案

当我想将一些“复杂”对象与 Pester 进行比较时,我使用 ConvertTo-Json。这并不理想,因为如果类型不匹配,可能会出现一些误报,但它通常可以完成工作。

$Expected = @(
[PSCustomObject]@{Name1 = 'Text1';Name2 = 'Text2'}
[PSCustomObject]@{Name1 = 'Text1';Name2 = 'Text2'}
)
$Actual = @(
[PSCustomObject]@{Name1 = 'Text1';Name2 = 'Text2'}
[PSCustomObject]@{Name1 = 'Text1';Name2 = 'Text2'}
)

Describe 'comparing arrays' {
Context 'Assert-Equivalent' {
it 'should be green' {
Assert-Equivalent -Actual ($Expected | ConvertTo-Json) -Expected ($Expected | ConvertTo-Json)
}
it 'should be green' {
Assert-Equivalent -Actual ($Actual | ConvertTo-Json) -Expected ($Expected | ConvertTo-Json)
}
it 'should be red' {
$Wrong = @(
[PSCustomObject]@{Name1 = 'Text1';Name2 = 'Text2'}
[PSCustomObject]@{Name1 = 'WROMG';Name2 = 'Text2'}
)
Assert-Equivalent -Actual ($Wrong | ConvertTo-Json) -Expected ($Expected | ConvertTo-Json)
}
}
Context 'Should be' {
it 'should be green' {
($Expected | ConvertTo-Json) | Should -Be ($Expected | ConvertTo-Json)
}
it 'should be green' {
($Actual | ConvertTo-Json) | Should -Be ($Expected | ConvertTo-Json)
}
it 'should be red' {
$Wrong = @(
[PSCustomObject]@{Name1 = 'Text1';Name2 = 'Text2'}
[PSCustomObject]@{Name1 = 'WROMG';Name2 = 'Text2'}
)
($Wrong | ConvertTo-Json) | Should -Be ($Expected | ConvertTo-Json)
}
}
}

关于arrays - 如何在 Pester 中将两个数组与自定义对象进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50870891/

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