Siddharth Shankar
Siddharth Shankar

Reputation: 539

Determine two lists are equal without caring about ordering Mockito

I have got into a situation where I am stubbing through when-then to match a list but I am getting error most of the times due to ordering issue.

List<String> myListToMatch = new ArrayList<String>();
myListToMatch .add("1");
myListToMatch .add("2");
when(obj.methodName(eq(myListToMatch))).thenReturn("someStringValue");

Due to ordering as in the called method the list go as ["2","1"] which is not returning "someStringValue" as per the above stubbing which is affecting my test case. Any help is appreciated. I am using Mockito library. I dont have any hamcrest dependency(dont want to add any).

I tried sorting in the code and it works but I dont want to update my code if there is way or some kind of argument matcher which I can use in when-then stubbing.

Upvotes: 3

Views: 1613

Answers (2)

Andy Turner
Andy Turner

Reputation: 140319

Assuming you actually care about the number of occurrences, the easiest way is to construct a Map<String, Long>, where the key is an element in the list, and the value is the number of occurrences of that element:

Map<String, Long> map =
    list.stream()
        .collect(Collectors.groupingBy(a -> a, Collectors.counting()));

Construct this map for each of the expected and actual lists, then compare them for equality.

Upvotes: 0

Chaitanya
Chaitanya

Reputation: 3638

First of all, if you do not care about the ordering of elements, you could go for a Set instead. Alternatively you could also follow the implementation given in the following answer that closely aligns with your problem statement.

If you are using Java 8, and newer versions of Mockito you could write the following piece of code. Its taken from here

when(
   mock.method(argThat(t -> t.containsAll(Arrays.asList("1","2"))))
).thenReturn(myValue);

Please let me know if this answers your question.

Upvotes: 1

Related Questions