Assertj-core: isEqualToComparingFieldByField does not deal with Infinity

Created on 8 Jan 2019  路  5Comments  路  Source: assertj/assertj-core

Summary

When using isEqualToComparingFieldByField, if two fields have the same Infinity value the objects are not considered equal. This does not seem to be the expected behaviour.
This is due to Infinity not being handled in the DoubleComparator.
NaN are not handled either, but I can see why this would be more controversial.

Example

       class A {
           double a = Double.POSITIVE_INFINITY;
       }

        assertThat(new A()).isEqualToComparingFieldByField(new A());

Proposed fix

In both DoubleComparator and FloatComparator, closeEnough could be changed to:

    private static boolean closeEnough(Double x, Double y, double epsilon) {
        if (x.doubleValue() == y.doubleValue()) {
            return true;
        } else if (Double.isNaN(x) && Double.isNaN(y)) {
            return true;
        } else {
            return Math.abs(x - y) <= epsilon;
        }
    }

Most helpful comment

Yup, happy to contribute it.

All 5 comments

I agree with x.doubleValue() == y.doubleValue() but I indeed think it should not compare NaN, users can always register their own double comparator to get that specific behaviour.

Would you like to contribute this improvement?

Yup, happy to contribute it.

Here's a workaround people can use while they wait for 3.12 to be released. You can add a comparator for doubles that correctly handles infinite values. This assumes, of course, that your infinite values are type Double, not double.

assertThat(widget1)
    .usingComparatorForType(Double::compare, Double.class)
    .isEqualToComparingFieldByField(widget2);

@mrog true, FYI 3.12.0 is going to be released in two weeks or so.

Was this page helpful?
0 / 5 - 0 ratings