如何使用Epsilon的assertEquals在JUnit中断言两个双精度? [英] How to Assert Two doubles in JUnit Using assertEquals with Epsilon?

查看:142
本文介绍了如何使用Epsilon的assertEquals在JUnit中断言两个双精度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不推荐使用双精度的assertEquals。我发现应该使用Epsilon的表格。这是因为不可能100%严格的双打。但无论如何我需要比较两个双打(预期和实际结果),但我不知道该怎么做。

assertEquals for doubles is deprecated. I found that the form with Epsilon should be used. It is because of impossible 100% strictness of doubles. But anyway I need to compare two doubles (expected and actual result), but I don't know how to do it.

目前我的测试看起来像: / p>

At the moment my test looks like:

@Test
public void testCalcPossibleDistancePercentageCount() {
    int percentage = 100;
    assertEquals("Wrong max possible value for %" + percentage, 110.42, processor.calcPossibleValue(percentage));
    percentage = 75;
    /*corresponding assertions*/
}

这是3个双倍值我接收,我想用JUnit检查:110.42,2760.5和10931.58。
JUnit测试应该如何使用断言?我在方法中计算得到它们:

Here are 3 double values I receive and which I want to check with JUnit: 110.42, 2760.5 and 10931.58. How should JUnit test look like with assertions for them? I receive them as a result of calculation in a method:

processor.calcPossibleValue(allowed_percentage){return /*Some weird formulae here*/;}


推荐答案

您需要添加第四个参数到 assertEquals 调用:两个双精度应被视为相等的阈值。您的电话应如下所示:

You need to add a fourth parameter to the assertEquals call: the threshold within which two doubles should be considered "equal". Your call should look like this:

assertEquals("Wrong max possible value for %" + percentage, 110.42,
        processor.calcPossibleValue(percentage), 0.01);

上述调用表明如果 processor.calcPossibleValue返回的值(百分比) 110.42 的±0.01范围内,则这两个值被认为是相等的。您可以更改此值,使其小到应用程序所需的值。

The above call would indicate that if the value returned by processor.calcPossibleValue(percentage) is within ± 0.01 of 110.42, then the two values are considered equal. You can change this value to make it as small as is necessary for your application.

请参阅JUnit文档以获取更多信息。

See the JUnit documentation for more information.

这篇关于如何使用Epsilon的assertEquals在JUnit中断言两个双精度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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