Question

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?

Était-ce utile?

La solution

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

Autres conseils

If you look at source code for assertEquals you will find out that it is overloaded for arrays and it does specialized equality test for them:

https://android.googlesource.com/platform/external/junit/+/android-4.2.1_r1/src/org/junit/internal/ComparisonCriteria.java

so it:

  1. Tests whether their sizes match
  2. Test each element for equality
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top