In the following code the last test fails:
@Unroll
def "each #map"(Map map) {
expect:
map.each{ assert it.value != null }
where:
_ | map
_ | [foo: 1, bar: 1]
_ | [foo: 1, bar: null]
_ | [:]
}
..with the message:
Condition not satisfied:
map.each{ assert it.value != null }
| |
[:] [:]
I would like to treat an empty map as a pass.
I'm aware that I can use "every". I.e.
@Unroll
def "every #map"(Map map) {
expect:
map.every{ it.value != null }
where:
_ | map
_ | [foo: 1, bar: 1]
_ | [foo: 1, bar: null]
_ | [:]
}
However the failure messages are less attractive. Rather than list the bad value, the list the entire collection. This isn't too bad when the only values are "foo" and "bar" but it's very hard to read when dealing with large lists.
I.e.
2nd case with each:
Condition not satisfied:
it.value != null
| | |
| null false
bar=null
2nd case with every:
Condition not satisfied:
map.every{ it.value != null }
| |
| false
[foo:1, bar:null]
It there a way to use use an assert loop and while treating an empty map as a pass?
Your test fails for a good reason. Just check what the following expression [:].each { it.value != null }
returns. It returns the input empty map. And Groovy Truth is straightforward in this case - an empty map evaluates to false
boolean value.
If you want to use map.each {}
with explicit assertions you may add a small "exception" to your condition - you can make an explicit expectation that empty map is valid, and for all remaining cases you check all values inside the non-empty map.
@Unroll
def "each #map"(Map map) {
expect:
map == [:] || map.each { assert it.value != null }
where:
_ | map
_ | [foo: 1, bar: 1]
_ | [foo: 1, bar: null]
_ | [:]
}