JUnit Assert with BigDecimal JUnit Assert with BigDecimal java java

JUnit Assert with BigDecimal


The official junit solution to assert that two BigDecimal are matematically equal is to use hamcrest.

With java-hamcrest 2.0.0.0 we can use this syntax:

    // import static org.hamcrest.MatcherAssert.assertThat;    // import org.hamcrest.Matchers;    BigDecimal a = new BigDecimal("100")    BigDecimal b = new BigDecimal("100.00")    assertThat(a,  Matchers.comparesEqualTo(b));

Hamcrest 1.3 Quick Reference


assertSamechecks if both objects are the same instance. assertEqualschecks if the numbers are equal in value and scale, that means i.e. 1000 is not equal to 1000.00. If you want to compare only the numeric value, you should use compareTo() method from BigDecimal.

For example:

BigDecimal bd1 = new BigDecimal (1000.00);BigDecimal bd2 = new BigDecimal (1000);org.junit.Assert.assertTrue(bd1.compareTo(bd2) == 0); 


Comparing BigDecimal with compareTo() works (as in: it ignore the scale and compare the actual number) but when unit testing it's useful to know what's the actual number, specially when the test fail.

An option I've used in this case is stripTrailingZeros() on both BigDecimal:

assertEquals(new BigDecimal("150").stripTrailingZeros(),                    otherBigDecimal.stripTrailingZeros());

What this function does is remove zeroes without changing the number, so "150" is converted in "1.5E+2": this way it doesn't matter if you have 150, 150.00 or other form in otherBigDecimal because they get normalized into the same form.

The only difference is a null in otherBigDecimal would give a NullPointerException instead of an assertion error.