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 ?
Since Mockito any(Class) and anyInt family matchers perform a type check, thus they won't match null arguments. Instead use the isNull matcher.
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.
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) .
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.
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);
This is a one-liner. Use the Hamcrest containsInAnyOrder
matcher.
when(myMock.myMethod(argThat(containsInAnyOrder(IN_PROGRESS, ABANDONED, EXPIRED))))
.thenReturn(myValue);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With