Reputation: 3
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 );
Upvotes: 0
Views: 1869
Reputation: 13924
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
.
Upvotes: 4