Mockito: Stubbing mechanics

Learn
Sep 10, 2024

--

When stubbing the behavior of a method of a class, you might think you need to specify the exact arguments for the method, and then you would be able to dictate that the stub returns so-and-so specific return value for that method.

Mockito is way more flexible than that, and provides multiple options. Let us take a closer look.

Argument matchers

Instead of directly specifying individual values, you can provide a matcher that translates to a set of possible values for the particular argument.

anyXXX

when(myInstance.myMethod(anyString(), anyInt()).thenReturn(false);

times — number of calls

verify(myInstance, times(2).myMethod(anyString(), anyString());

return — multiple values

when(myInstance.myMethod(anyString())).thenReturn(1,5,6,10);

when(myInstance.myMethod(anyString()).
thenReturn(1).
thenReturn(5).
thenReturn(6).
thenReturn(10)
;

verify — at least n times

verify(myIstance, atLeast(2)).myMethod(anyString());

verify — at most n times

verify(myInstance, atMost(3)).myMethod(anyString());

Matcher with eq

when(myIstance.method(Mockito.eq(10)).thenReturn(true);

Throw exception

Mockito.doThrow(new UnsupportedOperationException()).when(myInstance).myMethod(Mockito.eq(23));

--

--