检查对象列表是否相等,而不检查列表中的顺序 属性

Check lists of objects for equality without order check in their List property

先决条件:我正在将复杂的 JSON 反序列化为数据 class。目标 class 的层次结构有点复杂。

我有一个对象列表List。其中 ServiceFeature 如下(在 kotlin 中,但没关系):

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

如您所见,ServiceFeature 有一个“属性”属性,其中包含另一个“属性”列表。要点是列表中的属性可以按任何顺序排列。 有没有一种可靠的方法来比较 ServiceFeatures 的两个列表而无需从 List<Attribute?>

进行顺序检查

我正在尝试使用 assertJ 寻找解决方案。

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

如果您想保留顺序但比较(唯一)属性,您可以在比较时将它们转换为集合,请参阅 Easiest way to convert a List to a Set in Java

如果元素的顺序无关紧要,那么您可以使用 Set 而不是 List。话虽如此,您可以使用 containsExactlyInAnyOrder() method provided by AssertJ. This method expects var-args as an argument, so in order to convert list to array we can use toTypedArray along with spread operator 例如


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)
        }

    }
}