0
0
JUnittesting~15 mins

@Mock annotation in JUnit - Build an Automation Script

Choose your learning style9 modes available
Verify behavior of a service method using @Mock annotation
Preconditions (2)
Step 1: Create a test class for the service
Step 2: Annotate the repository interface field with @Mock
Step 3: Annotate the service class field with @InjectMocks
Step 4: Initialize mocks using MockitoAnnotations.openMocks(this) in a setup method
Step 5: Stub the repository method to return a fixed value when called
Step 6: Call the service method that uses the repository
Step 7: Verify the returned value matches the stubbed value
✅ Expected Result: The service method returns the stubbed value from the mocked repository, confirming @Mock works correctly
Automation Requirements - JUnit 5 with Mockito
Assertions Needed:
Assert that the service method returns the expected stubbed value
Verify that the repository method was called exactly once
Best Practices:
Use @Mock to create mock objects
Use @InjectMocks to inject mocks into the class under test
Initialize mocks in a @BeforeEach setup method
Use Mockito's when-thenReturn for stubbing
Use verify to check interactions with mocks
Automated Solution
JUnit
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;

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

class UserServiceTest {

    @Mock
    private UserRepository userRepository;

    @InjectMocks
    private UserService userService;

    @BeforeEach
    void setUp() {
        MockitoAnnotations.openMocks(this);
    }

    @Test
    void testGetUserNameReturnsStubbedValue() {
        // Arrange
        when(userRepository.findUserNameById(1)).thenReturn("Alice");

        // Act
        String result = userService.getUserName(1);

        // Assert
        assertEquals("Alice", result, "The service should return the stubbed user name");
        verify(userRepository, times(1)).findUserNameById(1);
    }
}

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

class UserService {
    private final UserRepository userRepository;

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

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

This test class demonstrates how to use the @Mock annotation to create a mock of UserRepository. The @InjectMocks annotation injects this mock into the UserService instance.

In the setUp method, MockitoAnnotations.openMocks(this) initializes the mocks before each test.

The test method testGetUserNameReturnsStubbedValue stubs the repository method findUserNameById to return "Alice" when called with 1.

Then it calls the service method and asserts the returned value matches the stubbed value. It also verifies the repository method was called exactly once.

This setup ensures the service behavior is tested in isolation from the real repository, using the mock created by @Mock.

Common Mistakes - 4 Pitfalls
Not initializing mocks with MockitoAnnotations.openMocks(this)
Using @Mock but not using @InjectMocks for the class under test
Stubbing methods after calling the service method
Using real implementations instead of mocks for dependencies
Bonus Challenge

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

Show Hint