Musings about this and that

December 4, 2008

JUnit-testing BigDecimals: watch your JUnit version

Filed under: Unit Testing, UnitTest — ajesse @ 11:55 am

Consider this test:

  public void testBigDecimalAssertEquals() {
    BigDecimal number1 = new BigDecimal("0.01");
    BigDecimal number2 = new BigDecimal("0.99");

    System.out.println("number1.equals(number2)= " + number1.equals(number2));
    assertEquals(number1, number2);
    System.out.println("  but JUnit thinks its equals...");
    assertTrue(number1.equals(number2));
    System.out.println(  "  only testing for BigDecimal.equals() == "
                       + "true will yield the correct result.");
  }

I definitely expected the assertEquals condition to report a failure, but…

In my Eclipse environment I had JUnit 4.3.1 loaded and the test only failed on the assertTrue condition.

After some download- and debug-sessions I learned that some JUnit-versions (> 3.8.x and < 4.4) had some code in the Assert.isEquals() method which caused this behaviour:

private static boolean isEquals(Object expected, Object actual) {
  if (expected instanceof Number && actual instanceof Number)
    return ((Number) expected).longValue() == ((Number) actual).longValue();
  return expected.equals(actual);
}

Versions before and after 4.4 do not check for a Number-instance, they just call the objects equals method.

Blog at WordPress.com.