从Groovy 1.8开始,如果键和值相同,我们可以检查一个Map是否等于另一个Map。 例如,在测试中非常方便。
def someMap = [age: 34, name: "Ted"]
assert someMap == [name: "Ted", age: 34]
今天,我一直盯着故障,同时测试了Grails控制器返回的一些x和y图形数据点,根据Spock的说法,其中两个Map在某种程度上是不相等的,即使断言的输出也看起来“相等”。
when:
controller.milkYield()
then:
response.json
and: "series are present"
def series = response.json
series.size() == 2
and: "realized series is correct"
...
and: "predicted series is correct"
def predictedSeries = series[1]
predictedSeries.values.size() == 2
predictedSeries.values[0] == [y:null, x:'Mar']
predictedSeries.values[1] == [y:121, x:'Apr']
导致:
Condition not satisfied:
predictedSeries.values[0] == [y:null, x:'Mar']
| | | |
| | | false
| | [y:null, x:Mar]
| [[y:null, x:Mar], [y:121, x:Apr]]
[values:[[y:null, x:Mar], [y:121, x:Apr]]]
为什么[y:null, x:Mar]
等于[y:null, x:Mar]
?
在明确检查之后
predictedSeries.values[0].x == 'Mar'
predictedSeries.values[0].y == null // <- better be null!
我再次想起我在Grails中使用NULL Object模式处理JSON数据。 时不时地咬我:-)
Condition not satisfied:
predictedSeries.values[0].y == null
| | | | |
| | | | false
| | | null (org.codehaus.groovy.grails.web.json.JSONObject$Null)
| | [y:null, x:Mar]
| [[y:null, x:Mar], [y:121, x:Apr]]
[values:[[y:null, x:Mar], [y:121, x:Apr]]]
这是一个JSONObject$Null
实例。 之所以存在,是因为它等效于JavaScript调用null的值 ,而Java的null等效于JavaScript调用undefined的值。
已经有很长时间的帖子已经描述了JSONObject.NULL
不等于null
行为。
JSONObject.NULL.equals(null) // true
JSONObject.NULL == null // false!!
当时建议您进行一些元类更改 。 似乎报道了GRAILS-7739(错误==和JSONObject.Null的asBoolean行为)说它早在Grails 2.2中就已修复。
至少已修复某些问题。 尽管您仍然不能执行JSONObject.NULL == null
,但是您可以将断言更改为使用Groovy Truth,因为!JSONObject.NULL
确实可以工作。
!predictedSeries.values[0].y
// or predictedSeries.values[0] == [y: JSONObject.NULL, x:'Mar'] if you like
当然,我应该记住(控制台)输出中的null始终是导致“ null”的String表示形式,例如JSONObject.NULL
的toString()
返回。
翻译自: https://www.javacodegeeks.com/2015/05/grails-jsonobject-null-more-or-less-equal-to-null.html