Skip to content

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

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.