如何使用 spock 框架执行相同顺序的映射
How to enforce maps of the same order using spock framework
下面的测试通过了,而我实际上希望看到它失败。该顺序对我的用例很重要。但是我认为 groovy 总是使用链表,所以排序应该是可测试的。
def "test foo"() {
given:
def a = [a: 1, c: 3, b: 2]
when:
def b = [a: 1, b: 2, c: 3]
then:
a == b
}
如果您想测试这两个 LinkedHashMap
实例中的键顺序,您可以执行以下操作:
def "test foo"() {
given:
def a = [a: 1, c: 3, b: 2]
when:
def b = [a: 1, b: 2, c: 3]
then: "make sure maps are equal"
a == b
and: "make sure entries are defined in the same order"
a.collect { it.key } == b.collect { it.key }
}
LinkedHashMap
不会覆盖 equals
方法(它使用 AbstractMap
class 中定义的方法,与 HashMap
等使用的方法相同)和它仅定义迭代顺序(将条目添加到地图的顺序)。
两个断言都可以简化为一个:
def "test foo"() {
given:
def a = [a: 1, c: 3, b: 2]
when:
def b = [a: 1, b: 2, c: 3]
then: "compare ordered list of map entries"
a.collect { it } == b.collect { it }
}
您可以在比较中使用 toMapString()
a.toMapString() == b.toMapString()
toMapString 将地图转换为字符串,这意味着顺序会影响比较
'[a:1, c:3, b:2]' == '[a:1, b:2, c:3]'
将 return 错误。
下面的测试通过了,而我实际上希望看到它失败。该顺序对我的用例很重要。但是我认为 groovy 总是使用链表,所以排序应该是可测试的。
def "test foo"() {
given:
def a = [a: 1, c: 3, b: 2]
when:
def b = [a: 1, b: 2, c: 3]
then:
a == b
}
如果您想测试这两个 LinkedHashMap
实例中的键顺序,您可以执行以下操作:
def "test foo"() {
given:
def a = [a: 1, c: 3, b: 2]
when:
def b = [a: 1, b: 2, c: 3]
then: "make sure maps are equal"
a == b
and: "make sure entries are defined in the same order"
a.collect { it.key } == b.collect { it.key }
}
LinkedHashMap
不会覆盖 equals
方法(它使用 AbstractMap
class 中定义的方法,与 HashMap
等使用的方法相同)和它仅定义迭代顺序(将条目添加到地图的顺序)。
两个断言都可以简化为一个:
def "test foo"() {
given:
def a = [a: 1, c: 3, b: 2]
when:
def b = [a: 1, b: 2, c: 3]
then: "compare ordered list of map entries"
a.collect { it } == b.collect { it }
}
您可以在比较中使用 toMapString()
a.toMapString() == b.toMapString()
toMapString 将地图转换为字符串,这意味着顺序会影响比较
'[a:1, c:3, b:2]' == '[a:1, b:2, c:3]'
将 return 错误。