Search code examples
javatestingjunitassertj

Compare two lists with elements field-by-field


I have the following structure

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;
}

none of the classes implements equals. I would like to compare two ComplexClazzs for equality independent of the ordering in the lists.

In my legacy code this is so far solved with

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

but I would like to get rid of the outdated unitils library and use e.g. assertj.

I tried with assertThat(actualResult).containsExactlyInAnyOrder(expectedResult); in combination with usingFieldByFieldElementComparator but could not make it work.

Any ideas how to compare theses objects?


Solution

  • Give a try to AssertJ recursive comparison and use ignoringCollectionOrder, ex:

    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);