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.
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); }
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);
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.
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.
Better write something like this:
assertEquals(23.0, 250.0, 0.0)
0.0 - it is delta. Read why yours methods are deprecated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With