即使预期结果正确,JUnit测试也会失败 [英] JUnit test fails even if the expected result is correct

查看:85
本文介绍了即使预期结果正确,JUnit测试也会失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图运行JUnit测试,但是它一直失败-即使代码应该通过测试也是如此.有什么想法吗?我已经把函数,转换因子和测试放了

I have tried to run the JUnit test, but it keeps failing - even if the code is supposed to pass the test. Any ideas why? I have put the function, the conversion factor and the test

这是测试:

private static MathContext mc = new MathContext( 12, RoundingMode.HALF_EVEN );
public static final BigDecimal testValue = new BigDecimal( 123456.1234567 );

@Test   
public final void testconvertFathomToMetersDM3() {      
    BigDecimal expectedResult = unitConverter.convertFathomToMetersDM3(testValue); 
    assertTrue( expectedResult.equals( new BigDecimal( 1.234561234567E+21, mc ) ) );   
}   

这是应该执行转换的方法:

This is the method that is supposed to do the conversion:

private BigDecimal result;  
private static MathContext mc = new MathContext( 12, RoundingMode.HALF_EVEN );

public final BigDecimal convertMetersToFathomDM3(BigDecimal value) {
    result = value.divide( ConversionFactors.FATHOM_DMA3, mc );
    return result;
}

这是我使用的转换因子:

Here is the conversion factor I have used:

public static final BigDecimal FATHOM_DMA3 = new BigDecimal( 1.875E+1 );

推荐答案

在测试浮点数的相等性时,通常存在一些与舍入错误有关的问题.为了解决此类问题,有一种 assertEquals 方法,该方法具有三个双精度参数,最后一个是增量.您可以尝试将assert语句更改为以下内容:

While testing equality of floating numbers there are often some issues concerning rounding errors. To solve this kind of problem there is an assertEquals method with three double parameters, of which the last is a delta. You can try changing your assert statement to the following:

final double delta = 0.00001;
BigDecimal result = unitConverter.convertFathomToMetersDM3(testValue); 
Assert.assertEquals(1.234561234567E+21, result.doubleValue(),  delta);

您应根据需要调整增量.增量定义为the maximum delta between expected and actual for which both numbers are still considered equal.

You should adjust delta to your needs. Delta is defined as the maximum delta between expected and actual for which both numbers are still considered equal.

这篇关于即使预期结果正确,JUnit测试也会失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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