JUnit 4.0 fun

| Tags: dev, java

The current IDEA Demetra builds now have built-in JUnit 4.0 support. Since the TestNG plugin hasn’t been updated for a while and it never was integrated into IDEA as good as the JUnit plugin. I decided to switch back to JUnit 4 for a private project of mine.

Switching from TestNG to JUnit 4 is not a big issue since JUnit imitates the annotations of TestNG and TestNG uses the Assert class from JUnit. OK, so switching was done in no time. Now let’s see whether all the tests still run. Under TestNG they all did. … Oh well, under JUnit 4 they don’t. Let’s see what the first failure is:

java.lang.AssertionError: expected:<1> but was:<1>
at org.junit.Assert.fail(Assert.java:58)
at org.junit.Assert.failNotEquals(Assert.java:259)
at org.junit.Assert.assertEquals(Assert.java:80)
at org.junit.Assert.assertEquals(Assert.java:88)
...

That’s kinda strange. What’s going on here. The test looks like that:

assertEquals(1, ingredient.getFromAmount(0).getAmount());

And there’s a an assert some lines earlier that looks very similar and succeeds:

assertEquals(1, ingredient.getConversionsCount());

So what’s going on here. Somewhere in the back of my head a light goes on. Looking into the Assert-class reveals that there aren’t any assertEquals-methods for longs and ints. You don’t need them. Autoboxing is used. Fine, but even with Autoboxing it should work, shouldn’t it. Not necessarily. ingredient.getFromAmount(0).getAmount() returns a long, which is then autoboxed into a Long. 1 is autoboxed into an Integer. Since new Long(1).equals(new Integer(1)) returns false, the test must fail.

I think the JUnit guys were a bit too fast with removing those assertEquals methods. Keeping them wouldn’t hurt anyone. Removing them will make it harder to move older projects from JDK 1.4 and JUnit 3 to JDK 5 and JUnit 4.

The fix for this issue is to make the 1 explicitely into a long like so:

assertEquals(1l, ingredient.getFromAmount(0).getAmount());

Now both – the expected and the actual value – are autoboxed to Longs and all is well.