Mockito @InjectMocks Example

1. Introduction

The Mockito framework offers the @InjectMocks annotation to automatically inject mock fields into the tested object. It simplifies the setup of test cases by reducing the boilerplate code for mock injections. The primary objective of @InjectMocks is to create an instance of the class you'd like to test and then inject into this instance the mock objects annotated with @Mock or @Spy.

2. Steps

1. Define a service class that depends on a repository class for its operation.

2. Create a test class.

3. Within the test class, create a mock for the repository.

4. Use @InjectMocks to inject the mock repository into the service class.

5. Define a test where we stub the mock repository's method and then call the service method that uses the repository.

6. Verify the interactions.

3. Mockito @InjectMocks Example

import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

// Service class that depends on a repository
class UserService {
    private UserRepository userRepository;

    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public String findUserNameById(Long userId) {
        return userRepository.getUserName(userId);
    }
}

interface UserRepository {
    String getUserName(Long userId);
}

public class UserServiceTest {
    // Create a mock instance of UserRepository
    @Mock
    UserRepository userRepository;

    // Inject the mock userRepository into userService
    @InjectMocks
    UserService userService;

    @Test
    public void testFindUserNameById() {
        // Initializing the mock objects
        MockitoAnnotations.initMocks(this);

        // Stubbing the mock to return "John Doe" for userId 1
        when(userRepository.getUserName(1L)).thenReturn("John Doe");

        String result = userService.findUserNameById(1L);
        assertEquals("John Doe", result);

        // Verifying the interaction with the mock
        verify(userRepository).getUserName(1L);
    }
}

Output:

The test will pass, and the returned value will be the stubbed value "John Doe".

4. Step By Step Explanation

1. We have a UserService class that relies on the UserRepository interface to fetch a user's name based on their ID.

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

3. We then use @InjectMocks to instantiate our UserService and inject the mock userRepository into it.

4. Before using these annotations, we initialize them with MockitoAnnotations.initMocks(this);.

5. Next, we stub our userRepository mock to return a value of "John Doe" when getUserName is called with an ID of 1.

6. In the testFindUserNameById method, we call the findUserNameById method of our userService and verify that the returned value matches our stubbed value.

7. Lastly, we ensure that our mock's getUserName method was indeed called with the argument 1L using the verify() method.


Comments