为什么在 JUnit 中不推荐使用 assertEquals(double,double)?

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

我想知道为什么 assertEquals(double, double) 被弃用了。

我使用了 import static org.junit.Assert.assertEquals; 并且我使用了 JUnit 4.11。

下面是我的代码:

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 双倍值。

有什么问题吗?

由于双精度问题,它已被弃用。

如果您注意到,还有另一种方法 assertEquals(double expected, double actual, double delta) 允许 delta 精度损失。

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.

assertEquals(double, double) 已弃用,因为 2 个双打可能相同,但如果它们是计算值,处理器可能会使它们的值略有不同。

如果你尝试这个,它会失败:assertEquals(.1 + .7, .8)这是使用英特尔® 处理器测试的

调用 deprecated method 将触发 fail("Use assertEquals(expected, actual, delta) to compare floating-point numbers"); 被调用。

人们解释但不提供样本...所以这对我有用:

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

0到底;

老问题,但这还没有说出来,可能会对某人有所帮助。

您可以使用 com.google.common.math.DoubleMath.fuzzyEquals(double a, double b, double tolerance) 来指定两个双打之间的距离。

我发现它对于我不想用很多小数位硬编码测试结果值的单元测试非常方便。