Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 331
NRJ Avatar asked Nov 24 '18 14:11

NRJ


People also ask

How do you compare double values in JUnit?

In fact, JUnit provides a set of comparing methods for common objects, collections, and primitive types, including dedicated methods to check double values equality: double epsilon = 0.000001d; assertEquals(d1, d2, epsilon);

What is double delta in assertEquals?

assertEquals(double expected, double actual, double delta) Asserts that two doubles are equal concerning a delta.

How many parameters does assertEquals () have?

Procedure assertEquals has two parameters, the expected-value and the computed-value, so a call looks like this: assertEquals(expected-value, computed-value); Note the order of parameters: expected-value and computed-value. Therefore, do not write the first call this way: assertEquals(C.

Is JUnit 5 faster than junit4?

JUnit 5 is 10x slower than JUnit 4 #880.


1 Answers

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);
like image 91
Necreaux Avatar answered Sep 25 '22 14:09

Necreaux