检查对象列表是否相等,而不在他们的List属性中进行订单检查

先决条件:我将一个复杂的json反序列化为数据类。 目标类有一个复杂的层次结构。

我有一个List List的列表。 哪里ServiceFeature是以下(它在kotlin,但没关系):

data class ServiceFeature( val flagValue: String?, val effectiveFlagValue: String?, val name: String?, val attributes: List<Attribute?>? ) 

正如你可以看到ServiceFeature有一个“属性”属性,其中包括另一个“属性”列表。 重点是列表中的属性可能是以任何顺序。 有没有一种可靠的方法来比较ServiceFeatures的两个列表,而无需从List中进行订单检查

我试图找到assertJ的解决方案。

先谢谢你。

如果顺序对于你的属性并不重要,而且它们是唯一的(即可能没有相同类型的多个属性),你可以将结构改为Set<Attribute?>而只是使用常规比较。

如果要保留顺序,但要比较(唯一)属性,则可以在比较时将它们转换为集合,请参阅在Java中将List转换为Set的最简单方法 。

如果元素顺序无关紧要,那么可以使用Set而不是List 。 话虽如此,您可以使用由AssertJ提供的containsExactlyInAnyOrder()方法。 这个方法需要var-args作为参数,所以为了将列表转换为数组,我们可以使用toTypedArray和扩展运算符 Eg

 import org.junit.Test import org.assertj.core.api.Assertions.* data class ServiceFeature( val flagValue: String?, val effectiveFlagValue: String?, val name: String?, val attributes: List? ) data class Attribute(val name: String?) class SimpleTest { @Test fun test() { val list1 = listOf(ServiceFeature("flagA", "effectiveFlagA", "foo", listOf(Attribute("a"), Attribute("b")))) val list2 = listOf(ServiceFeature("flagA", "effectiveFlagA", "foo", listOf(Attribute("b"), Attribute("a")))) list1.zip(list2).forEach { assertThat(it.first.name).isEqualTo(it.second.name) assertThat(it.first.effectiveFlagValue).isEqualTo(it.second.effectiveFlagValue) assertThat(it.first.name).isEqualTo(it.second.name) val toTypedArray = it.second.attributes!!.toTypedArray() // null-check as per your need assertThat(it.first.attributes).containsExactlyInAnyOrder(*toTypedArray) } } } 
Interesting Posts