Mockito @Mock Annotation Example

1. Introduction

Mockito is a widely used testing framework in the Java community that allows for the creation of mock objects in automated unit tests. 

The @Mock annotation is a cornerstone of Mockito, simplifying the process of mock creation. With this annotation, you can quickly create a mock instance of a class or interface, allowing you to focus on testing its interactions and behaviors.

2. Mockito @Mock Annotation Example

In this example, we'll create a simple service fetching user data. We won't be focusing on the actual implementation of fetching the data but will mock this behavior using Mockito's @Mock annotation. We'll then demonstrate how to stub and verify interactions with this mock.

import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;

class UserService {
    public String fetchUserName(Long userId) {
        // Dummy implementation. This method would typically fetch user details from a database.
        return "John Doe";

public class UserServiceTest {
    // Using @Mock annotation to create a mock instance of UserService
    UserService userService;

    public void testFetchUserName() {
        // Initializing the mock objects

        // Stubbing the mock to return "Mock User" when fetchUserName is called
        when(userService.fetchUserName(anyLong())).thenReturn("Mock User");

        String result = userService.fetchUserName(1L);
        assertEquals("Mock User", result);

        // Verifying the interaction with the mock


The test will pass, and the asserted value will match the stubbed value "Mock User".

3. Step By Step Explanation

1. First, we have a dummy UserService class with a method fetchUserName which ideally fetches user data from some data source.

2. In our UserServiceTest class, we create a mock of UserService using the @Mock annotation.

3. Before we use the mock, it's initialized using MockitoAnnotations.initMocks(this);.

4. We then stub our mock to return a value of "Mock User" when fetchUserName is called with any long value using when()...thenReturn().

5. In our test method testFetchUserName, we invoke the fetchUserName method of our mocked userService and assert that the returned value matches our stubbed value.

6. Finally, we verify that our mock's fetchUserName method was indeed called with the argument 1L using the verify() method.

4. Conclusion

The @Mock annotation is a shorthand way of creating mock objects. Instead of manually creating a mock using Mockito.mock(Class), you can annotate a field with @Mock to automatically create a mock instance.