JUnit-testing BigDecimals: watch your JUnit version

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

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s