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

ID : 20387

viewed : 9

Tags : javaarraysjunitassertionsjava

Top 5 Answer for java - Comparing arrays in JUnit assertions, concise built-in way?

vote vote

92

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.

vote vote

81

You can use Arrays.equals(..):

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

73

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.

vote vote

51

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:

java.lang.AssertionError:     Expected: is [<56>, <100>, <2000>]    but: was [<55>, <100>, <2000>] 

Top 3 video Explaining java - Comparing arrays in JUnit assertions, concise built-in way?

Related QUESTION?