[英]Check two lists for order equality after sorting elements of one 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
而不是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.