Mockito User Manual

Creating Mock Objects

Creating mock objects is the first step in using Mockito for testing. There are multiple ways to create mock objects, and developers can choose the appropriate method based on their needs.

Using the mock() Method

The most basic way is to use the static method mock() from the Mockito class to create mock objects. This method accepts a Class parameter and returns a mock instance of that class.

import static org.mockito.Mockito.*;

List<String> mockedList = mock(List.class);
Map<String, Integer> mockedMap = mock(Map.class);

Starting from Mockito 4.10.0, you can omit the Class parameter and the compiler will automatically infer the type.

List<String> mockedList = mock();

Using @Mock Annotation

The @Mock annotation provides a cleaner declaration style, especially useful when multiple mock objects need to be created in a test class. Using the annotation requires initializing the Mockito framework first.

public class UserServiceTest {
    @Mock
    private UserRepository userRepository;
    
    @Mock
    private EmailService emailService;
    
    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
    }
}

Using MockitoJUnitRunner can handle initialization automatically.

@RunWith(MockitoJUnitRunner.class)
public class UserServiceTest {
    @Mock
    private UserRepository userRepository;
}

Using JUnit 5's @ExtendWith annotation also achieves automatic initialization.

@ExtendWith(MockitoExtension.class)
public class UserServiceTest {
    @Mock
    private UserRepository userRepository;
}

Defining Method Behavior

Defining method behavior is also known as stubbing. It is used to specify what values should be returned or what exceptions should be thrown when mock objects are called.

Basic Return Value Stubbing

Use the when().thenReturn() chain syntax to define return values.

when(mockedList.size()).thenReturn(100);
when(mockedList.get(0)).thenReturn("first");
when(mockedList.get(1)).thenReturn("second");

You can define multiple consecutive return values, and each subsequent call will return different values.

when(mockedList.get(anyInt()))
    .thenReturn("first")
    .thenReturn("second")
    .thenThrow(new RuntimeException("Error"));

System.out.println(mockedList.get(0)); // outputs: first
System.out.println(mockedList.get(0)); // outputs: second
System.out.println(mockedList.get(0)); // throws exception

Defining Exception Throwing

Use thenThrow() to define exceptions that should be thrown when methods are called.

when(mockedList.get(0)).thenThrow(new IndexOutOfBoundsException("Index 0"));

For methods with void return type, use doThrow().

doThrow(new RuntimeException("Error")).when(mockedList).clear();

Using Answer for Custom Responses

If predefined return values are insufficient, you can implement the Answer interface to dynamically compute return values.

when(mockedList.get(anyInt())).thenAnswer(invocation -> {
    int index = invocation.getArgument(0);
    return "Value at index " + index;
});

Verifying Interactions

Verification is used to confirm that the code under test correctly interacts with mock objects as expected.

Basic Verification

Use verify() to check if a method was called.

mockedList.add("one");
verify(mockedList).add("one");

Verifying Call Count

You can verify how many times a method was called.

mockedList.add("one");
mockedList.add("one");
mockedList.add("one");

verify(mockedList, times(3)).add("one");       // exactly 3 times
verify(mockedList, atLeast(2)).add("one");     // at least 2 times
verify(mockedList, atMost(3)).add("one");      // at most 3 times
verify(mockedList, never()).add("two");        // never called
verify(mockedList, atLeastOnce()).add("one");  // at least once

Verifying Call Order

The InOrder verifier can check whether method calls were executed in a specific order.

InOrder inOrder = inOrder(mockedList);
inOrder.verify(mockedList).add("first");
inOrder.verify(mockedList).add("second");
inOrder.verify(mockedList).add("third");

Verifying Call Arguments

Argument matchers can be used to flexibly verify call arguments.

verify(mockedList).add(anyString());
verify(mockedList).get(anyInt());
verify(mockedList).contains(argThat(s -> s.length() > 5));

Argument Matchers

Mockito provides rich argument matchers for flexible matching of method parameters.

Built-in Matchers

anyInt()          // any integer
anyString()       // any string
any()             // any object
anyList()         // any list
anyMap()          // any map
isNull()          // null value
isNotNull()       // non-null value
eq(value)         // exact match
startsWith()      // starts with specified string
endsWith()        // ends with specified string
contains()        // contains specified string

Custom Matchers

Custom argument matchers can be created using the argThat() method.

when(mockedList.add(argThat(s -> s != null && s.length() > 3)))
    .thenReturn(true);

Using Spy

Unlike mocks, spies retain most of the real object's behavior while allowing specific methods to be stubbed.

Creating a Spy

List<String> realList = new ArrayList<>();
List<String> spyList = spy(realList);

Or use the @Spy annotation.

@Spy
private List<String> list = new ArrayList<>();

Defining Spy Behavior

Unlike mocks, you need to be careful when using when() with spies because it may affect real method calls. It is recommended to use the doReturn().when() syntax.

doReturn(100).when(spyList).size();

Spies call real methods unless explicitly stubbed.

spyList.add("element");  // real method will be called
verify(spyList).add("element");  // verification passes

Using @InjectMocks

The @InjectMocks annotation is used to automatically create the object under test and inject fields annotated with @Mock or @Spy into it.

@RunWith(MockitoJUnitRunner.class)
public class UserServiceTest {
    @Mock
    private UserRepository userRepository;
    
    @Mock
    private EmailService emailService;
    
    @InjectMocks
    private UserService userService;
    
    @Test
    public void testCreateUser() {
        User user = new User("testUser");
        when(userRepository.save(any(User.class))).thenReturn(user);
        
        User result = userService.createUser("testUser");
        
        assertEquals("testUser", result.getUsername());
        verify(userRepository).save(any(User.class));
    }
}

Using ArgumentCaptor

ArgumentCaptor is used to capture arguments passed during method calls for more detailed assertions.

@Mock
private List<String> mockedList;

@Test
public void testCaptureArgument() {
    mockedList.add("test");
    
    ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
    verify(mockedList).add(captor.capture());
    
    assertEquals("test", captor.getValue());
}

When a method is called multiple times, you can capture all arguments.

mockedList.add("first");
mockedList.add("second");
mockedList.add("third");

ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
verify(mockedList, times(3)).add(captor.capture());

assertEquals(3, captor.getAllValues().size());
assertEquals("second", captor.getAllValues().get(1));

BDD Style Testing

Mockito supports Behavior-Driven Development (BDD) style testing using given().willReturn() syntax.

import static org.mockito.BDDMockito.*;

@Test
public void testBddStyle() {
    // Given
    given(mockedList.get(0)).willReturn("first");
    
    // When
    String result = mockedList.get(0);
    
    // Then
    assertEquals("first", result);
}

Common Usage Patterns

Testing Void Methods

@Test
public void testVoidMethod() {
    doNothing().when(mockedList).clear();
    mockedList.clear();
    verify(mockedList).clear();
}

Mocking Method Chains

@Test
public void testMethodChaining() {
    when(mockedList.iterator()).thenReturn(Collections.emptyIterator());
    
    Iterator<String> iterator = mockedList.iterator();
    assertFalse(iterator.hasNext());
}

Mocking Exception Handling

@Test(expected = RuntimeException.class)
public void testException() {
    when(mockedList.get(0)).thenThrow(new RuntimeException("Error"));
    mockedList.get(0);
}

Best Practices

When using Mockito, follow best practices to ensure test code quality and maintainability. Do not mock types you own or value objects, as this breaks the真实性 of tests. Only mock necessary dependencies to maintain test真实性. Each test method should focus on testing one feature. Organize test code properly using @Before for common setup. Verification should be适度, focusing on important interactions rather than verifying every method call.