我正在使用spock在groovy中编写一些测试,我需要检查两个大小相等的列表中的值是否正确相互映射,并且其中一个列表中没有重复的值。我目前正在执行以下操作:
我在list1中找到一个给定的值,然后在list2中搜索其对应的值。如果我在list2中找到相应的值,则要删除它。我对列表(list1)上的每个位置重复此操作,最后我要确认list2为空。如果list2最后不为空,则表明存在一些未删除的意外值或重复项。
我正在执行以下操作
def list1 = ["a", "b", "c", "d"]
def list2 = ["dog", "goat", "wolf", "fox"]
list1.size() == list2.(size)
list1.size().times() {
if (list1.contains("a")) {
if (list2.contains("dog")) {
println(it + " found dog.... removing")
list2.remove("dog")
println(list2)
}
if (list1.contains("b")) {
if (list2.contains("goat")) {
println(it + " found goat.... removing")
list2.remove("goat")
println(list2)
}
}
if (list1.contains("c")) {
if (list2.contains("wolf")) {
println(it + " found wolf.... removing")
list2.remove("wolf")
println(list2)
}
}
if (list1.contains("d")) {
if (list2.contains("fox")) {
println(it + " found fox.... removing")
list2.remove("fox")
println(list2)
}
}
}
}
list2.isEmpty()
这似乎可行,但我想知道是否有一种更有效的方法来做到这一点?
Spock的优点是,您可以将断言分为多个部分。
首先检查正确的映射。然后检查其余列表中是否没有其他映射。
then: 'correct mapping'
list1.remove("a") == list2.remove("dog")
list1.remove("b") == list2.remove("goat")
list1.remove("c") == list2.remove("wolf")
list1.remove("d") == list2.remove("fox")
and: 'no additional mapping'
list1.isEmpty()
list2.isEmpty()
transpose(List)
的Groovy默认方法GroovyCollections.transpose(List)
,则只需一行代码:GroovyCollections.transpose(List)