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

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.


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;


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.

Tags:

Java

Junit

Junit4