0
0
JUnittesting~15 mins

@InjectMocks annotation in JUnit - Build an Automation Script

Choose your learning style9 modes available
Automate unit test using @InjectMocks to inject mock dependencies
Preconditions (3)
Step 1: Create a mock instance of the repository interface using @Mock
Step 2: Create an instance of the service class using @InjectMocks to inject the mock repository
Step 3: Stub the repository method to return a fixed value
Step 4: Call the service method that uses the repository
Step 5: Verify the service method returns the expected value based on the stubbed repository
✅ Expected Result: The service method returns the expected value from the mocked repository without null pointer exceptions
Automation Requirements - JUnit 5 with Mockito
Assertions Needed:
Assert that the service method returns the stubbed value
Verify that the repository method was called exactly once
Best Practices:
Use @ExtendWith(MockitoExtension.class) to enable Mockito annotations
Use @Mock for dependencies
Use @InjectMocks for the class under test
Use Mockito's when-thenReturn for stubbing
Use verify to check interactions
Keep test methods small and focused
Automated Solution
JUnit
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

@ExtendWith(MockitoExtension.class)
public class UserServiceTest {

    @Mock
    UserRepository userRepository;

    @InjectMocks
    UserService userService;

    @Test
    void testGetUserNameReturnsStubbedName() {
        // Arrange: stub repository method
        when(userRepository.findUserNameById(1)).thenReturn("Alice");

        // Act: call service method
        String result = userService.getUserName(1);

        // Assert: verify returned value
        assertEquals("Alice", result);

        // Verify repository method was called once
        verify(userRepository, times(1)).findUserNameById(1);
    }
}

// Supporting classes
interface UserRepository {
    String findUserNameById(int id);
}

class UserService {
    private final UserRepository userRepository;

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

    public String getUserName(int id) {
        return userRepository.findUserNameById(id);
    }
}

This test class uses @ExtendWith(MockitoExtension.class) to enable Mockito annotations.

The @Mock annotation creates a mock instance of UserRepository.

The @InjectMocks annotation creates an instance of UserService and injects the mocked UserRepository into it.

In the test method, we stub the repository method findUserNameById to return "Alice" when called with 1.

We then call the service method getUserName and assert it returns "Alice".

Finally, we verify that the repository method was called exactly once.

This setup ensures the service is tested in isolation with controlled dependencies.

Common Mistakes - 4 Pitfalls
{'mistake': 'Not using @ExtendWith(MockitoExtension.class) causing @Mock and @InjectMocks not to work', 'why_bad': "Mockito annotations won't be processed, mocks won't be created, leading to NullPointerException", 'correct_approach': 'Always add @ExtendWith(MockitoExtension.class) on the test class to enable Mockito annotations'}
{'mistake': 'Manually instantiating the class under test instead of using @InjectMocks', 'why_bad': "Mocks won't be injected automatically, dependencies will be null or real instances", 'correct_approach': 'Use @InjectMocks to let Mockito create the class and inject mocks automatically'}
Forgetting to stub mock methods before calling service methods
Using field injection in the class under test instead of constructor injection
Bonus Challenge

Now add data-driven testing with 3 different user IDs and expected names

Show Hint