JUnit test fails even if expected result is correct

I tried to run the JUnit test, but it continues to fail - even if the code needs to pass the test. Any ideas why? I set the function, conversion coefficient and test

This is a 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 should perform 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 used:

 public static final BigDecimal FATHOM_DMA3 = new BigDecimal( 1.875E+1 ); 
0
java junit
source share
1 answer

When checking the equality of floating numbers, problems with rounding errors often arise. To solve this problem, there is an assertEquals method with three double parameters, the last of which is a delta. You can try changing the assert statement to the following:

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

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

+4
source share

All Articles