Why is assertEquals(double,double) deprecated in JUnit?

JavaJunitJunit4

Java Problem Overview


I was wondering why assertEquals(double, double) is deprecated.

I used import static org.junit.Assert.assertEquals; and I used JUnit 4.11.

Below is my code:

import org.junit.Test;
import static org.junit.Assert.assertEquals;


public class AccountTest {

@Test
public void test() {
	Account checking = new Account(Account.CHECKING);
	checking.deposit(1000.0);
	checking.withdraw(100.0);
	assertEquals(900.0, checking.getBalance());
   }
}

checking.getBalance() returns a double value.

What could be wrong?

Java Solutions


Solution 1 - Java

It's deprecated because of the double's precision problems.

If you note, there's another method assertEquals(double expected, double actual, double delta) which allows a delta precision loss.

JavaDoc:

> Asserts that two doubles are equal to within a positive delta. If they are not, an AssertionError is thrown. If the expected value is infinity then the delta value is ignored.NaNs are considered equal: assertEquals(Double.NaN, Double.NaN, *) passes > > ... > > delta - the maximum delta between expected and actual for which both numbers are still considered equal.

Solution 2 - Java

People explain but don't give samples... So here goes what worked for me:

@Test
public void WhenMakingDepositAccountBalanceIncreases() {
	Account account = new Account();
	account.makeDeposit(10.0);
	assertEquals("Account balance was not correct.", 10.0, account.getBalance(), 0);
}

The 0 in the end;

Solution 3 - Java

assertEquals(double, double) is deprecated because the 2 doubles may be the same but if they are calculated values, the processor may make them slightly different values.

If you try this, it will fail: assertEquals(.1 + .7, .8). This was tested using an Intel® processor.

Calling the deprecated method will trigger fail("Use assertEquals(expected, actual, delta) to compare floating-point numbers"); to be called.

Solution 4 - Java

Old question but this hasn't been said yet and might help someone.

You can use com.google.common.math.DoubleMath.fuzzyEquals(double a, double b, double tolerance) which allows you to specify how close the two doubles should be to each other.

I found it very handy for unit tests where I don't want to hardcode test result values with a lot of decimal places.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionjsh6303View Question on Stackoverflow
Solution 1 - JavaCodebenderView Answer on Stackoverflow
Solution 2 - JavaVictor AugustoView Answer on Stackoverflow
Solution 3 - JavaEricView Answer on Stackoverflow
Solution 4 - Javasteven35View Answer on Stackoverflow