0

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

This is 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 );
Jeff Bowman
  • 90,959
  • 16
  • 217
  • 251
  • 1
    Please fix your code... – Sotirios Delimanolis Dec 12 '13 at 04:18
  • What exactly is the problem you are facing? Also, Format your code. – Nishan Dec 12 '13 at 04:23
  • Where is `testValue` coming from? And where is `mc` coming from? What is its actual value when passed in? That may be causing your failures - if `testValue` is a property of the test class, then you've got invalid data. – Makoto Dec 12 '13 at 04:33
  • private static MathContext mc = new MathContext( 12, RoundingMode.HALF_EVEN ); public static final BigDecimal testValue = new BigDecimal( 123456.1234567 ); – Rob Willey Dec 12 '13 at 04:40
  • 1
    Stylistically, the variable you call "expectedResult" is in fact the actual result from the method that you're testing. Your constant that you're comparing it to is the expected result. Furthermore JUnit provides an assertEquals(expected,actual) which will usually give a more meaningful failure message than assertTrue(). – Charlie Dec 12 '13 at 05:12

1 Answers1

4

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);

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.

Community
  • 1
  • 1
phlogratos
  • 13,234
  • 1
  • 32
  • 37