在下面的代码中,最后一个测试失败了:
@Unroll
def "each #map"(Map map) {
expect:
map.each{ assert it.value != null }
where:
_ | map
_ | [foo: 1, bar: 1]
_ | [foo: 1, bar: null]
_ | [:]
}
..与消息:
Condition not satisfied:
map.each{ assert it.value != null }
| |
[:] [:]
我想将空 map 视为通行证。
我知道我可以使用“every”。即
@Unroll
def "every #map"(Map map) {
expect:
map.every{ it.value != null }
where:
_ | map
_ | [foo: 1, bar: 1]
_ | [foo: 1, bar: null]
_ | [:]
}
然而,失败消息的吸引力较低。与其列出坏值,不如列出整个集合。当唯一的值是“foo”和“bar”时,这还算不错,但在处理大型列表时很难阅读。
即
每个案例的第二个案例:
Condition not satisfied:
it.value != null
| | |
| null false
bar=null
第二个案例:
Condition not satisfied:
map.every{ it.value != null }
| |
| false
[foo:1, bar:null]
有没有一种方法可以使用断言循环,同时将空映射视为通过?
最佳答案
如果您对看起来更具声明性并在断言中给出适当错误的东西感兴趣,您也可以尝试:
[a: null, b: 2, c: 3].findAll{ it.value == null }.isEmpty()
它以映射的形式为您提供所有有问题的 null
值(注意:输出来自 Groovy assert
而不是 Spock):
assert([a: null, b: 2, c: 3].findAll{ it.value == null }.isEmpty())
| |
['a':null] false
at x.run(x.groovy:1)
优势取决于您的用例:
- 您看到所有违规条目
- 您会看到违规值的所有键
关于groovy - 在空 map 上调用每个失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55265854/