assertEquals(Double, Double) 和 assertEquals(double, double, delta) 之间的 Junit 区别 [英] Junit difference between assertEquals(Double, Double) and assertEquals(double, double, delta)

查看:26
本文介绍了assertEquals(Double, Double) 和 assertEquals(double, double, delta) 之间的 Junit 区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 junit 测试断言两个 Double 对象如下:

I had a junit test asserting two Double objects with the following:

Assert.assertEquals(Double expected, Double result);

这很好,然后我决定将其更改为使用原始 double 代替,结果证明已弃用,除非您还提供增量.

This was was fine then I decided to change it to use the primitive double instead which turned out to be deprecated unless you also provide a delta.

所以我想知道在这个 assertEquals 中使用 Double 对象或原始类型有什么区别?为什么使用没有 delta 的对象可以,但不推荐使用没有 delta 的原语?Java 是否在后台做了一些已经考虑了默认增量值的事情?

so what I am wondering is what is the difference between using the Double object or the primitive type in this assertEquals? Why is using the objects without a delta ok but then using the primitives without a delta is deprecated? Is Java doing something in the background which already has a default delta value taken into account?

谢谢.

推荐答案

没有 在 JUnit 中使用签名声明方法

assertEquals(Double expected, Double result);

然而,有一个对象是通用的:

There is one, however, generic for objects:

assertEquals(Object expected, Object result);

这会调用对象的 equals 方法,正如您所料,不建议使用它来比较 Double 对象.

This calls the objects' equals method and as you can expect, it is not recommended to use this for comparing Double objects.

对于双打,正如您所观察到的,绝对有必要使用增量进行比较,以避免浮点舍入问题(已在其他一些答案中进行了解释).如果您使用带有 double 参数

For doubles, as you observed, it is absolutely necessary to use a delta for comparison, to avoid issues with floating-point rounding (explained already in some other answers). If you use the 3-argument version of assertEquals with double arguments

assertEquals(double expected, double actual, double delta);

您的 Double 将被静默地拆箱为 double 并且一切正常(并且您的测试不会意外失败 :-).

your Doubles will get silently unboxed to double and everything will work fine (and your tests won't fail unexpectedly :-).

这篇关于assertEquals(Double, Double) 和 assertEquals(double, double, delta) 之间的 Junit 区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆