0
0
JUnittesting~10 mins

@Mock annotation in JUnit - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test uses the @Mock annotation to create a mock object for a dependency. It verifies that the method under test calls the mocked dependency correctly and returns the expected result.

Test Code - JUnit 5 with Mockito
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.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

@ExtendWith(MockitoExtension.class)
public class UserServiceTest {

    @Mock
    UserRepository userRepository;

    @Test
    void testGetUserName() {
        // Arrange
        UserService userService = new UserService(userRepository);
        when(userRepository.findNameById(1)).thenReturn("Alice");

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

        // Assert
        assertEquals("Alice", name);
        verify(userRepository).findNameById(1);
    }
}

class UserService {
    private final UserRepository userRepository;

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

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

interface UserRepository {
    String findNameById(int id);
}
Execution Trace - 7 Steps
StepActionSystem StateAssertionResult
1Test starts and MockitoExtension initializes the test classUserServiceTest instance created with userRepository mocked-PASS
2UserService instance created with mocked userRepositoryUserService ready to use mocked dependency-PASS
3Mock userRepository is stubbed to return 'Alice' when findNameById(1) is calledMock behavior set-PASS
4Call getUserName(1) on UserServiceUserService calls mocked userRepository.findNameById(1)-PASS
5Verify returned name is 'Alice'Result from getUserName is 'Alice'assertEquals("Alice", name)PASS
6Verify userRepository.findNameById(1) was called at least onceMock interaction recordedverify(userRepository).findNameById(1)PASS
7Test ends successfullyAll assertions passed-PASS
Failure Scenario
Failing Condition: The mock userRepository does not return the expected value or method is not called
Execution Trace Quiz - 3 Questions
Test your understanding
What does the @Mock annotation do in this test?
ACreates a fake UserRepository object to control its behavior
BRuns the real UserRepository code
CInjects a real database connection
DMarks the test method to be ignored
Key Result
Using @Mock allows you to isolate the class under test by replacing dependencies with controllable mock objects, making tests faster and more reliable.