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

查看:1889
本文介绍了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);

这很好然后我决定改变它以使用原始的双倍而不是原来的不推荐使用,除非你也提供了一个delta。

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是否在后台执行某些已考虑默认delta值的事情?

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中没有断言方法带签名

There is NO assert method in JUnit with the signature

assertEquals(Double expected, Double result);

然而,对象有一个通用:

There is one, however, generic for objects:

assertEquals(Object expected, Object result);

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

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

对于双打,就像你一样观察到,绝对有必要使用delta来进行比较,以避免浮点舍入问题(在其他一些答案中已有解释)。如果你使用 assertEquals 的3参数版本与 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天全站免登陆