I'm following Kent Beck's Test Driven Development by Example.
The relevant chapter can be found as a preview online here.
Kent writes:
Can we use a two-element array containing the two currencies as the key? Does Array.equals() check to see if the elements are equal?
public void testArrayEquals() {
assertEquals(new Object[] {"abc"}, new Object[] {"abc"});
}
Nope. The test fails, so we have to create a real object for the key
However when I run the test it passes.
I thought that assertEquals would check Array.equals() which checks for the same object, rather than contents, therefore the test would fail, but it doesn't (at least not for me).
On the other hand:
System.out.println( new Object[]{"abc"}.equals(new Object[]{"abc"}) );
Prints false as expected...
Eclipse tells me that assertEquals(Object[], Object[]) is now deprecated, but for the sake of understanding, why is the test passing for me now?
Arrays don't override equals
, so you get reference equality - that's why your System.out.println
call is printing false
. However, JUnit's method is asserting that the arrays are logically equal, i.e. that they're the same size, and each element pair within them is equal. That's almost always what you want when you're writing a test involving arrays.
I suspect Kent wrote the bit of that book before JUnit had this useful behaviour, however. (Indeed, I expect the book predates the overload existing at all.)
See more on this question at Stackoverflow