簡體   English   中英

檢查對象列表是否相等,無需在其 List 屬性中進行順序檢查

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

先決條件:我正在將復雜的 JSON 反序列化為數據類。 目標類有一些復雜的層次結構。

我有一個對象列表列表。 其中 ServiceFeature 如下(在 kotlin 中,但無關緊要):

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

如您所見, ServiceFeature有一個“屬性”屬性,其中包含另一個“屬性”列表。 要點是列表中的屬性可以按任何順序排列。 有沒有一種可靠的方法來比較兩個ServiceFeatures列表,而無需從List<Attribute?>進行順序檢查List<Attribute?>

我正在嘗試使用 assertJ 找到解決方案。

如果順序對您的屬性無關緊要並且它們是唯一的(即可能沒有多個相同類型的屬性),您可以將結構更改為Set<Attribute?>而只是使用常規比較。

如果您想保留順序但比較(唯一)屬性,您可以在比較時將它們轉換為集合,請參閱Java 中將列表轉換為集合的最簡單方法

如果元素的順序無關緊要,那么您可以使用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)
        }

    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM