简体   繁体   中英

Precision of Junit 5's assertEquals with double

Looks like exact doubles aren't considered equal in junit 5 The following code fails in junit 5

public void testDouble() {        
    org.junit.jupiter.api.Assertions.assertEquals(87.91622222222225d, 87.91622222222225d, 0.0);
}

and the same in junit 4, passes the test

public void testDouble() {
    org.junit.Assert.assertEquals(87.91622222222225d, 87.91622222222225d, 0.0);
}

Is there a good explanation for this difference?

To elaborate on an answer in the comments, the error message given is:

org.opentest4j.AssertionFailedError: positive delta expected but was: <0.0>

This error is potentially confusing. I initially interpreted it as meaning that my delta was higher than 0.0 and that a non-zero delta fails when the values are equal. (This would be very strange indeed)

The error message in fact means that the delta provided (0.0) is an unsupported bad value. It has nothing to do with the two values provided which may or may not be equal and are not compared.

The solutions are to either use the method that does not have a delta parameter or provide a non-zero delta which is probably safer with doubles. Either of these should work:

org.junit.jupiter.api.Assertions.assertEquals(87.91622222222225d, 87.91622222222225d);
org.junit.jupiter.api.Assertions.assertEquals(87.91622222222225d, 87.91622222222225d, 0.00000000001d);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM