Friday, January 12, 2007

Beware Of JUnit's assertEquals for Primitive Array

If you run the below JUnit test case


int[] intArr00 = {1};
int[] intArr01 = {1};
assertEquals(intArr00, intArr01);

It looks simple, and should pass. However, it will throw AssertionFailedError. Why? It is because the compiler calls assertEquals(Object expected, Object actual) as array of primitive type is an Object. Since we do not overwrite the Object.equals(Object obj) method, so you are actually running:

public boolean equals(Object obj) {
return (this == obj);
}

intArr00 and intArr01 are two different references, thus it returns false. I have a method to return array of int, but now, I can't create a test case with official JUnit library. Hope I have time to look at some extension library of JUnit.



4 comments:

David Saff said...

CK,

Good catch! This will actually be fixed in JUnit 4.3, to be released within the next month. The bug report is here:

http://sourceforge.net/tracker/index.php?func=detail&aid=1619941&group_id=15278&atid=115278

Thanks,

David Saff

Andres Almiray said...

There is an alternative while you wait for JUnit 4.3: ArrayAssertions from EZMorph. This helper class will also let you compare an int[] to an Integer[] and viceversa. Please take a look at http://ezmorph.sourceforge.net/apidocs/

Anonymous said...

Thanks for posting about this. It quickly answered why I was having trouble.

Cheers.

Anonymous said...

That one almost got me too. It's a pity that NetBeans + Maven still defaults to JUnit 3.8. Could be worse: could be a false pass.

For now you'll just have to live with assertTrue(java.util.Arrays.equals(intArr00, intArr01));