Home » Java » Comparing arrays in JUnit assertions, concise built-in way?

Comparing arrays in JUnit assertions, concise built-in way?

Posted by: admin November 30, 2017 Leave a comment


Is there a concise, built-in way to do equals assertions on two like-typed arrays in JUnit? By default (at least in JUnit 4) it seems to do an instance compare on the array object itself.

EG, doesn’t work:

int[] expectedResult = new int[] { 116800,  116800 };
int[] result = new GraphixMask().sortedAreas(rectangles);
assertEquals(expectedResult, result);

Of course, I can do it manually with:

assertEquals(expectedResult.length, result.length);
for (int i = 0; i < expectedResult.length; i++)
    assertEquals("mismatch at " + i, expectedResult[i], result[i]);

..but is there a better way?


Use org.junit.Assert‘s method assertArrayEquals:

import org.junit.Assert;

Assert.assertArrayEquals( expectedResult, result );

If this method is not available, you may have accidentally imported the Assert class from junit.framework.


You can use Arrays.equals(..):

assertTrue(Arrays.equals(expectedResult, result));


Assert.assertArrayEquals("message", expectedResult, result)


I prefer to convert arrays to strings:

                Arrays.toString(new int[] { 7, 8, 9, 3 }));

this way I can see clearly where wrong values are. This works effectively only for small sized arrays, but I rarely use arrays with more items than 7 in my unit tests.

This method works for primitive types and for other types when overload of toString returns all essential information.


I know the question is for JUnit4, but if you happen to be stuck at JUnit3, you could create a short utility function like that:

private void assertArrayEquals(Object[] esperado, Object[] real) {
    assertEquals(Arrays.asList(esperado), Arrays.asList(real));     

In JUnit3, this is better than directly comparing the arrays, since it will detail exactly which elements are different.


Using junit4 and Hamcrest you get a concise method of comparing arrays. It also gives details of where the error is in the failure trace.

import static org.junit.Assert.*
import static org.hamcrest.CoreMatchers.*;


assertThat(result, is(new int[] {56, 100, 2000}));

Failure Trace output:

   Expected: is [<56>, <100>, <2000>]
   but: was [<55>, <100>, <2000>]