AssertEquals 2 Lists ignore order
arrays, assertion, java, junit, unit-testing
Solution
As you mention that you use Hamcrest, So I would pick one of the collection Matchers
import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
import static org.junit.Assert.assertThat;
public class CompareListTest {
@Test
public void compareList() {
List<String> expected = Arrays.asList("String A", "String B");
List<String> actual = Arrays.asList("String B", "String A");
assertThat("List equality without order",
actual, containsInAnyOrder(expected.toArray()));
}
}
Problem
That should be really simple question I believe. But somehow I can't find answer in Google. Assume that I have 2 Lists of Strings. First contains "String A" and "String B", second one contains "String B" and "String A" (notice difference in order). I want to test them with JUnit to check whether they contains exactly the same Strings. Is there any assert that checks equality of Strings that ignore order? For given example org.junit.Assert.assertEquals throws AssertionError ``` java.lang.AssertionError: expected:<[String A, String B]> but was:<[String B, String A]> ``` Work around is to sort Lists firstly and then pass them to assertion. But I want my code to be as simple and clean as possible. I use Hamcrest 1.3, JUnit 4.11, Mockito 1.9.5.