[英]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.