本文正在参加「Java主题月 - Java Debug笔记活动」,详情查看 活动链接
问题:为什么JUnit不推荐使用assertEquals(double,double)了?
我想知道为什么assertEquals(double, double)已经不推荐使用了。
我使用导入静态的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()
返回一个double值.
这有什么问题吗?
回答一
他们解释但不提供例子…下面是我的例子:
@Test
public void WhenMakingDepositAccountBalanceIncreases() {
Account account = new Account();
account.makeDeposit(10.0);
assertEquals("Account balance was not correct.", 10.0, account.getBalance(), 0);
}
0在末尾
回答二
assertEquals(double, double)
已被弃用,因为这两个double可能是相同的,但如果它们是计算出来的值,处理器可能会使它们的值略有不同。
如果您尝试这样做,它将失败: assertEquals(.1 + .7, .8)
.这是使用英特尔®处理器进行的测试。
调用已弃用的方法将导致失败("Use assertEquals(expected, actual, delta) to compare floating-point numbers");。
回答三
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的精度问题,它被弃用了。
如果你注意到,还有另一个方法assertEquals(double expected, double actual, double delta)
,它允许精度的损失。
回答三
这是个老问题了,但还没人提出来,这也许能帮到别人。
你可以用com.google.common.math.DoubleMath.fuzzyEquals(double a, double b, double tolerance)
来指定两个双精度数之间的差值。
我发现它对于单元测试非常方便,因为我不想硬编码小数点后面有很多位的测试结果值。
文章翻译自Stack Overflow:stackoverflow.com/questions/3…