Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matching List in any order when mocking method behavior with Mockito

I have a test using Mockito that has a very strange behavior : it works in debug but fails when running normally. After some investigation, I realized it's because I am mocking methods behavior, passing a list of elements to match. But for some reason, order in the list is not always the same so it doesn't match and what I expect my mock to return is not returned, because the 2 lists are not "equals"

 when(mockStatusCalculatorService.calculateStatus(Arrays.asList(IN_PROGRESS, ABANDONNED,EXPIRED))).thenReturn(ConsolidatedStatus.EXPIRED);

In my case, order of elements to match doesn't matter. So how can I specify this when configuring my mock ?

like image 799
Vincent F Avatar asked Nov 30 '16 08:11

Vincent F


People also ask

What can I use instead of Mockito matchers?

Since Mockito any(Class) and anyInt family matchers perform a type check, thus they won't match null arguments. Instead use the isNull matcher.

Can the Mockito Matcher methods be used as return values?

Mockito requires that we provide all arguments either by matchers or exact values. There are two more points to note when we use matchers: We can't use them as a return value; we require an exact value when stubbing calls.

How do Mockito matchers work?

Matchers return dummy values such as zero, empty collections, or null . Mockito tries to return a safe, appropriate dummy value, like 0 for anyInt() or any(Integer. class) or an empty List<String> for anyListOf(String. class) .

What does Mockito any () do?

Mockito allows us to create mock objects and stub the behavior for our test cases. We usually mock the behavior using when() and thenReturn() on the mock object.


2 Answers

Adding an answer for newer versions of Mockito and Java 8

when(
   mock.method(argThat(t -> t.containsAll(Arrays.asList(IN_PROGRESS, ABANDONED, EXPIRED))))
).thenReturn(myValue);
like image 161
shinjw Avatar answered Sep 19 '22 16:09

shinjw


This is a one-liner. Use the Hamcrest containsInAnyOrder matcher.

when(myMock.myMethod(argThat(containsInAnyOrder(IN_PROGRESS, ABANDONED, EXPIRED))))
    .thenReturn(myValue);
like image 28
Dawood ibn Kareem Avatar answered Sep 19 '22 16:09

Dawood ibn Kareem