Mockito 101
Mockito is a mocking framework that lets you write beatiful tests with clean and simple API. It biases toward minimal specifications, makes different behaviors look different, and displays clear error messages.
Creating Mocks
To create a mock using Mockito, simply annotate mocks with @Mock
and call MockitoAnnotations.initMocks(this)
.
import org.mockito.Mock; import org.mockito.MockitoAnnotations; public class FooClassTest { @Mock mockFoo; public void setUp() { MockitoAnnotations.initMocks(this); ... } ... }
Stubbing values
Stubbing values can stimulate the behavior of exsiting code or be a temporary substitute for yet-to-be-developed code. By default, for all methods that return value, mock returns null, an empty collection or appropriate primitive/primitive wrapper value (e.g: 0, false, …). You can override the stubbing values as below. Once stubbed, the method will always return stubbed value regardless of how many times it is called. For a method with a void return, ususally we do not need to stub it.
import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.when; ... // a method that returns values when(mockFoo.someCall()).thenReturn(someValue); when(mockFoo.someCall()).thenThrow(new FooException()); // a method with a void return doThrow(new FooException()).when(mockFoo).voidMethodThatThrows();
Verifying a method was called
// call the subject under test verify(mockFoo, times(2)).someCall(); verify(mockFoo).someCall(); verify(mockFoo).callWithVoidReturnType();
What is the difference between “stubbying” and “verifying”? In a nutshell, “stubbing” should be used for the items that you don’t really care about, but they are necessary to make the test pass. In contrast, “verifying” should be used to verify the behavior.
Verifying the Order of Calls to a Single Object
InOrder order1 = Mockito.inOrder(mockFoo); order1.verify(mockFoo).firstCall(); order1.verify(mockFoo).thirdCall(); InOrder order2 = Mockito.inOrder(mockFoo); order2.verify(mockFoo).secondCall(); order2.verify(mockFoo).fifthCall();
Verifying the Order of Calls Across Multiple Objects
Foo mockFoo = Mockito.mock(Foo.class); Bar mockBar = Mockito.mock(Bar.class); // call the subject under test InOrder order = Mockito.inOrder(mockFoo, mockBar) order.verify(mockFoo).firstCall(); order.verify(mockBar).secondCall();
Verifying That Only the Expected Calls Were Made
In general, tests for no more interactions should be rare.
// call the subject under test verify(mockFoo).expectedCall(); verify(mockFoo).someOtherExpectedCall(); verifyNoMoreInteractions(mockFoo);
Verifying That Specific Calls Are Not Made
Testing that a specific call was not made is often better than checking for “no more calls.”
// call the subject under test verify(mockStream, never()).close();
Matchers
We can use matchers for mocked method parameters when ==
and equals
cannot be used to match a parameter, either for stubbing or verifying. If you find that you need complicated matchers, consider simplifying your subject under test or your tests, or consider using a hand-rolled fake instead of a mock.
import static org.mockito.Mockito.*; // Both of these forms use "equals" when(mockFoo.set("blah", 2)).thenReturn(value); when(mockFoo.set(eq("blah"), eq(2))).thenReturn(value); when(mockFoo.set(contains("la"), eq(2))).thenReturn(value); when(mockFoo.set(eq("blah"), anyInt())).thenReturn(value); when(mockFoo.set(anyObject(), eq(2))).thenReturn(value); when(mockFoo.set(isA(String.class), eq(2))).thenReturn(value); when(mockFoo.set(same(expected), eq(2))).thenReturn(value); ArgumentCaptor<String> sArg = ArgumentCaptor.forClass(String.class); when(mockFoo.set(sArg.capture(), eq(2))).thenReturn(value); ... // returns last captured value String capturedString = sArg.getValue(); List<String> capturedStrings = sArg.getAllValues();
Partial Mocks
When using spy
or CALLS_REAL_METHODS
, you may want to use the alternative stubbing syntax that does not call the existing method or stub: doReturn("The spy has control.").when(mockFoo).aMethod()
.
import org.mockito.Mockito; Foo mockFoo = Mockito.spy(new Foo()); // Note: instance, not class. // Note: "when" calls the real method, see tip below. when(mockFoo.aMethod()).thenReturn("The spy has control."); // call the subject under test verify(mockFoo).aMethod(); // Verify a call to a real method was made. verify(mockFoo).someRealMethod(); // Alternative construct, that will fail if an unstubbed abstract // method is called. Foo mockFoo = Mockito.mock(Foo.class, Mockito.CALLS_REAL_METHODS);
Reference: | Mockito 101 from our JCG partner Yifan Peng at the PGuru blog. |