Core Java

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 {

  public void setUp() {

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()).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();

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);

InOrder order2 = Mockito.inOrder(mockFoo);

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)

Verifying That Only the Expected Calls Were Made

In general, tests for no more interactions should be rare.

// call the subject under test

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();


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 a call to a real method was made.
// 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.

Yifan Peng

Yifan is a senior CIS PhD student in University of Delaware. His main researches include relation extraction, sentence simplification, text mining and natural language processing. He does not consider himself of a Java geek, but all his projects are written in Java.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button