簡體   English   中英

逐個字段比較兩個列表與元素

[英]Compare two lists with elements field-by-field

我有以下結構

public class ComplexClazz {

    private List<A> a;
    private List<B> b;
}

public class A {
    private String someString;
    private List<C> c;
}

public class B {
   private BigDecimal someBigDecimal;
}

public class C {
   private String someString;
   private D d;
}

public class D {
   private String someString;
   private Integer someInt;
}

沒有一個類實現等於。 我想比較兩個ComplexClazz的相等性,而與列表中的順序無關。

在我的遺留代碼中,這到目前為止已解決

ReflectionAssert.assertReflectionEquals(expectedResult, actualResult, ReflectionComparatorMode.LENIENT_ORDER);

但我想擺脫過時的unitils庫並使用例如assertj。

我試過assertThat(actualResult).containsExactlyInAnyOrder(expectedResult); 結合usingFieldByFieldElementComparator但無法使其工作。

任何想法如何比較這些對象?

嘗試AssertJ 遞歸比較並使用ignoringCollectionOrder ,例如:

public class Person {
   String name;
   List<Person> friends = new ArrayList<>();
   // no equals method
 }

 Person sherlock1 = new Person("Sherlock Holmes");
 sherlock1.friends.add(new Person("Dr. John Watson"));
 sherlock1.friends.add(new Person("Molly Hooper"));

 Person sherlock2 = new Person("Sherlock Holmes");
 sherlock2.friends.add(new Person("Molly Hooper"));
 sherlock2.friends.add(new Person("Dr. John Watson"));

 // assertion succeeds as friends collection order is ignored in the comparison
 assertThat(sherlock1).usingRecursiveComparison()
                      .ignoringCollectionOrder()
                      .isEqualTo(sherlock2);

 // assertion fails as friends collection order is not ignored in the comparison
 assertThat(sherlock1).usingRecursiveComparison()
                      .isEqualTo(sherlock2);

暫無
暫無

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

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