Video in progress

Strong Junior 🧪 Testing

In Mockito, what happens if you mix any() with an exact value in one call?

Mockito throws InvalidUseOfMatchersException: if a matcher is used for one argument, all the other arguments have to be matchers too. You fix it by wrapping the exact value in eq(...).

📖 Answer

// fails: 2 matchers expected, 1 given
when(rates.convert(any(), "USD")).thenReturn(BigDecimal.ONE);

// correct
when(rates.convert(any(), eq("USD"))).thenReturn(BigDecimal.ONE);

The reason is in how Mockito works internally. any() actually returns null (or 0) and records the matcher on an internal stack. Then Mockito compares the number of arguments with the number of matchers on the stack. If they're mixed, it can't tell which argument belongs to which matcher.

This mechanism leads to another gotcha: if you use a matcher outside when/verify, for example by storing it in a variable, the stack gets corrupted and the error shows up somewhere completely different.

var anyUser = any(User.class);   // don't do this

One more nuance: any() also matches null, while any(User.class) does not match null in Mockito 2+. If you do need null, use isNull().