Java – JUnit: use parameterized types – arrays to assert the equality of collections
I try to assert the equality of the following sets:
String[] arr1= new String[] { "1","2","3" }; Collection<String[]> coll1= Arrays.asList(arr1,arr1); String[] arr2 = new String[] { "1","3" }; Collection<String[]> coll2 = Arrays.asList(arr2,arr2); assertEquals(coll1,coll2);
However, I got the opposite result - assertion error The problem is using object The equals () method checks whether arrays are equal, which actually checks for references to significantly different arrays
Is there a convenient way I can use JUnit or guava to solve this problem?
Edit: note that I want to compare the collection object, not the array itself
Solution
This is where hamcrest came to rescque This is Javadoc link I recommend using isarraycontininginorder
So
assertThat(coll1,IsArrayContainingInOrder.arrayContaining(coll2));
Sorry, the above applies to arrays, but the following applies to collections
assertThat(coll1,IsIterableContainingInOrder.contains(coll2.toArray()));
This uses isiterablecontaininginorder
For reference only, I find that using hamcrest matchers is so elegant that I rarely use non hamcrest tests So all my tests are like this
assertThat(myValue,is(true)); assertThat(myValue,equalTo("something")); assertThat(myList,IsIterableContainingInAnyOrder.containsInAnyOrder(first,second,third));
About soap boxes