Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Junit difference between assertEquals(Double, Double) and assertEquals(double, double, delta)

I had a junit test asserting two Double objects with the following:

Assert.assertEquals(Double expected, Double result);

This was was fine then I decided to change it to use the primitive double instead which turned out to be deprecated unless you also provide a delta.

so what I am wondering is what is the difference between using the Double object or the primitive type in this assertEquals? Why is using the objects without a delta ok but then using the primitives without a delta is deprecated? Is Java doing something in the background which already has a default delta value taken into account?

Thanks.

like image 990
James Thomas Avatar asked Jun 28 '12 10:06

James Thomas


People also ask

What is Delta in assertEquals in JUnit?

From the JUnit javadoc: delta - the maximum delta between expected and actual for which both numbers are still considered equal. It's probably overkill, but I typically use a really small number, e.g. private static final double DELTA = 1e-15; @Test public void testDelta(){ assertEquals(123.456, 123.456, DELTA); }

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 the difference between assertEquals and assertSame?

The explanation is here – assertEquals() uses equals() method to validate if the two objects are equal whereas assertSame() uses the operator == to validate if two objects are equal. Both of these approaches vary; hence the results are different as well.

What is Delta in assertEquals for float?

You have to provide a delta to the assertion for Floats: Assert.assertEquals(expected, actual, delta) While delta is the maximum difference (delta) between expected and actual for which both numbers are still considered equal.


1 Answers

Better write something like this:

assertEquals(23.0, 250.0, 0.0)  

0.0 - it is delta. Read why yours methods are deprecated.

like image 132
Morozov Avatar answered Sep 18 '22 08:09

Morozov