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

Comparing arrays in JUnit assertions, concise built-in 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));


I prefer to convert arrays to strings:

Assert.assertEquals(                Arrays.toString(values),                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.