fl0w
fl0w

Reputation: 3897

Java - Deep comparison of objects without implementing the equals method in JUnit Tests

How to "deep"-compare two objects that do not implement the equals method based on their field values in a test?

In my example i have two objects from two different versions of an XML Schema that differ only in the version, in my test i want to show that a dozer-mapped result equals the original. The auto generated classes don't implement the equals method.

my.new.schema.Element new = mapper.map(old, my.new.schema.Element.class);

assertEquals(old, new); //obviously doesn't work

Upvotes: 3

Views: 2434

Answers (1)

fl0w
fl0w

Reputation: 3897

The easiest way is to use AssertJ's recursive comparison function:

assertThat(new).usingRecursiveComparison().isEqualTo(old);

See AssertJ doc for details: https://assertj.github.io/doc/#basic-usage

Prerequisites for using AssertJ:

import:

import static org.assertj.core.api.Assertions.*;

maven dependency:

    <!-- test -->
    <dependency>
        <groupId>org.assertj</groupId>
        <artifactId>assertj-core</artifactId>
        <version>3.19.0</version>
        <scope>test</scope>
    </dependency>

Upvotes: 9

Related Questions