在JUnit中的float和double值上使用assertTrue是否可以? [英] Is it ok to use assertTrue on float and double values in JUnit?

查看:227
本文介绍了在JUnit中的float和double值上使用assertTrue是否可以?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在float上使用assertEquals方法,并且日食表示该方法已过时.因此,可以接受以下替代方法吗?

I tried using the assertEquals method on a float and eclipse says that the method was depreciated. Therefore, is the following alternative acceptable?

Assert.assertTrue("Total does not match expected total :",
                                            receipt.getTotal() == 32.19f);

是否有特定的原因为什么不能在测试中使用assertEquals比较两个浮点数或双精度数?

Is there a specific reason why assertEquals must not be used to compare two floats or doubles in a test?

通常,在JUnit中断言两个十进制值相等的最佳方法是什么.我正在使用4.10版本的JUnit

In general, what is the best way to assert the equality of two decimal values in JUnit. I am using the 4.10 release of JUnit

推荐答案

通常,您可以将基本类型与==进行比较,但对于浮点值,两个值看起来可以相同(当格式化为字符串时),但是可以是两个不同的值.您应该使用 assertEquals(预期的,实际的增量).请参阅 JUnit:assertEquals以获得双精度值的答案.

In general you can compare primitive types with ==, but with floating point values, two values can look the same (when formatted as a string) but be two different values. You should be using assertEquals(expected, actual, delta). See the answer to JUnit: assertEquals for double values.

由于双精度(和浮点)计算不一定精确,因此您可以使用增量(有效误差范围)进行比较.

Because double (and float) calculations are not necessarily exact, you can compare using a delta (effectively a margin of error).

这篇关于在JUnit中的float和double值上使用assertTrue是否可以?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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