Problem
When a Hashtable
用作输入Should
,Pester 只输出类型名而不输出内容:
Describe 'test' {
It 'test case' {
$ht = @{ foo = 21; bar = 42 }
$ht | Should -BeNullOrEmpty
}
}
Output:
Expected $null or empty, but got @(System.Collections.Hashtable).
预期输出如:
Expected $null or empty, but got @{ foo = 21; bar = 42 }.
Cause
看着纠缠源,测试输入由私有函数格式化Format-Nicely
,它只是投射到String
如果值类型是Hashtable
。这归结为调用Hashtable::ToString()
,它只输出类型名称。
解决方法
作为一种解决方法,我目前正在从中派生一个类Hashtable
覆盖ToString
方法。在将输入传递给之前Should
,我将它投射到这个自定义类。这让 Pester 称我被覆盖ToString
格式化测试结果时的方法。
BeforeAll {
class MyHashTable : Hashtable {
MyHashTable( $obj ) : base( $obj ) {}
[string] ToString() { return $this | ConvertTo-Json }
}
}
Describe 'test' {
It 'test case' {
$ht = @{ foo = 21; bar = 42 }
[MyHashTable] $ht | Should -BeNullOrEmpty
}
}
现在 Pester 输出Hashtable
JSON 格式的内容,这对我来说已经足够了。
Question
有没有更优雅的方式来自定义 Pester 输出Hashtable
,这不需要我更改每个测试用例的代码?