【问题标题】:Check lists of objects for equality without order check in their List property检查对象列表是否相等,无需在其 List 属性中进行顺序检查
【发布时间】:2017-11-07 14:43:43
【问题描述】:

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

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

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

如您所见,ServiceFeature 有一个“属性”属性,其中包括另一个“属性”列表。要点是列表中的属性可能是任何顺序。 有没有一种可靠的方法来比较两个ServiceFeatures 列表而无需从List&lt;Attribute?&gt; 进行订单检查

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

【问题讨论】:

    标签: java kotlin assertj


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢,在数据类中将列表更改为设置就像一个魅力 val attributes: List&lt;Attribute?&gt;? -&gt; val attributes: Set&lt;Attribute?&gt;?
    【解决方案2】:

    如果元素的顺序无关紧要,那么您可以使用Set 而不是List。话虽如此,您可以使用 AssertJ 提供的containsExactlyInAnyOrder() 方法。此方法需要 var-args 作为参数,因此为了将列表转换为数组,我们可以使用 toTypedArray 和 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)
            }
    
        }
    }
    

    【讨论】:

    • 谢谢,我试过这个方法。它适用于数组,但在我的情况下,我有一个对象数组,其中有一个数组作为属性。在我的情况下,断言在检查 List for ServiceFeature 时失败
    • 您可以调整方法来比较列表,查看更新的答案
    猜你喜欢
    • 2019-11-04
    • 2022-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 2015-10-17
    • 2012-03-26
    • 1970-01-01
    相关资源
    最近更新 更多