This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

Question: Why does JUnit not recommend using assertEquals(double,double)?

I wonder why assertEquals(double, double) are no longer recommended.

I use the import static org. Junit. Assert. AssertEquals; And I use JUnit 4.11.

Here is my code:

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


public class AccountTest {

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

Check.getbalance () returns a double value. What’s wrong with that?

Answer a

They explain but don’t provide examples… Here’s my example:

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

0 at the end

Answer two

AssertEquals (double, double) has been deprecated because the two doubles may be the same, but the processor may make their values slightly different if they are computed values.

If you try to do so, it will fail: assertEquals(.1 +.7,.8). This test was conducted using an Intel ® processor.

Calling deprecated methods will fail (“Use assertEquals(expected, actual, delta) to compare floating-point numbers”); .

Answer three

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.

Double is deprecated because of its accuracy.

If you notice, there is another method, assertEquals(double Expected, double actual, double delta), which allows for a loss of precision.

Answer three

It’s an old question, but no one has asked it yet, and it might help someone else.

You can use com.google.com to mon. Math. DoubleMath. FuzzyEquals (double a, b double, double how) to specify the difference in value between two doubles.

I find it very handy for unit testing, because I don’t want to hardcode test result values with many bits behind the decimal point.

The article translated from Stack Overflow:stackoverflow.com/questions/3…