Search code examples
javaunit-testingtestingjunitassertj

AssertJ - The method isEqualToComparingFieldByFieldRecursively don't work with RuntimeException object


Summary

The method isEqualToComparingFieldByFieldRecursively don't work with RuntimeException object. The check always return true even if we change the RuntimeException message in the expected RuntimeException.

Not working example (always true)

assertThat(caughtException).as("The Runtime exception")
            .usingComparatorForType(ComparatorCollection.getDateComparator(MAX_ALLOWABLE_SEC_FOR_EQ),
                    LocalDateTime.class)
            .usingComparatorForType(ComparatorCollection.getXmlDateComparator(MAX_ALLOWABLE_SEC_FOR_EQ),
                    XMLGregorianCalendar.class)
            .isEqualToComparingFieldByFieldRecursively(expectedResults));
            // caughtException.message and expectedResults.message are different but return true

Working example

assertThat(caughtException).as("The Runtime exception")
            .usingComparatorForType(ComparatorCollection.getDateComparator(MAX_ALLOWABLE_SEC_FOR_EQ),
                    LocalDateTime.class)
            .usingComparatorForType(ComparatorCollection.getXmlDateComparator(MAX_ALLOWABLE_SEC_FOR_EQ),
                    XMLGregorianCalendar.class)
            .isEqualToComparingFieldByFieldRecursively(expectedResults)
            // The recursively check don't work with the RuntimeException message
            .isEqualToComparingOnlyGivenFields(expectedResults, "message");

We have make some tests and the second example work (when we force the check of the attribut message).


Solution

  • This is an old limitation of the code retrieving the fields to compare which ignored any type in java.lang (to avoid comparing Object field by field).

    This is too drastic and needs to be loosen, this bug has been created to track the issue https://github.com/joel-costigliola/assertj-core/issues/1224.