AssertJ using Recursive Comparison

Make sure you know and Use AssertJ, it’s Magic!

AssertJ usingRecursiveComparison

https://assertj.github.io/doc/#basic-usage

assertThat(studentA_).isEqualTo(studentA);

Fails because even though Address object is equal in value, it is not equal in reference

But assertion assertThat(studentA_).usingRecursiveComparison().isEqualTo(studentA); passes because it will compare recursively the Address fields

AssertJ using Recursive Comparison , ignoring certain fileds

Let’s say that You have a Student and an Address Entity

public class Student {

    private Integer id;
    private String name;
    private LocalDate joinDate;

    private Address address;
}
public class Address {

    private String street;
    private int streetNo;

    /*JPA ForeignKey*/
//    @OneToOne()
//    @JoinColumn(name = "student_id", referencedColumnName = "id", nullable 
    @ToString.Exclude
    @EqualsAndHashCode.Exclude
    private Student student;

    private List<Inhabitant> inhabitants;
}
  • But in your AddressDTO you don’t have the field StudentDTO

You can instruct AssertJ, to compare all the fields EXCPET some fields

        assertThat(studentA_).usingRecursiveComparison()
                .ignoringFields("address.student")
                .ignoringFields("address.inhabitants.address")
                .isEqualTo(studentA);

Please see this Git Repo for Details
https://github.com/razvangvr/openapi.server/blob/master/src/test/java/org/example/StudentMapperTest.java