I want to test if some list of strings is generated correctly by creating unit tests using JUnit.
I have 2 lists of strings (one list in my code is private static final, let's say list1) with the same elements (the same elements can multiply) in a different order:
List<String> list1 = Arrays.asList("a","b","c");
List<String> list2 = Arrays.asList("c","a","b");
assertThat(list1 , containsInAnyOrder(list2));
This is not working and the junit test returns that the first element is not matching.
I am probably using the containsInAnyOrder
method wrong.
containsInAnyOrder(java.util.Collection<Matcher<? super T>> itemMatchers)
I don't know how to implement this Matcher
.
I don't want to use this type of function as it is only ok for a small amount of elements:
containsInAnyOrder(T... items)
You can first sort both the List
and then compare the sorted List
s.
List<String> list1 = Arrays.asList("a","b","c");
List<String> list2 = Arrays.asList("c","a","b",);
Collections.sort(list1);
Collections.sort(list2);
assertEquals( list1, list2 ); // true