0
0
JUnittesting~10 mins

Mock objects in JUnit - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test uses a mock object to simulate a dependency and verifies that the service method calls the dependency correctly and returns the expected result.

Test Code - JUnit with Mockito
JUnit
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;

class UserServiceTest {

    interface UserRepository {
        String getUserEmail(int userId);
    }

    static class UserService {
        private final UserRepository userRepository;

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

        String getUserEmail(int userId) {
            return userRepository.getUserEmail(userId);
        }
    }

    @Test
    void testGetUserEmail() {
        // Create mock
        UserRepository mockRepo = mock(UserRepository.class);

        // Define behavior
        when(mockRepo.getUserEmail(1)).thenReturn("user@example.com");

        // Inject mock into service
        UserService userService = new UserService(mockRepo);

        // Call method
        String email = userService.getUserEmail(1);

        // Verify result
        assertEquals("user@example.com", email);

        // Verify interaction
        verify(mockRepo).getUserEmail(1);
    }
}
Execution Trace - 7 Steps
StepActionSystem StateAssertionResult
1Test startsJUnit test runner initialized-PASS
2Creates mock object for UserRepository using Mockito.mock()Mock UserRepository instance created-PASS
3Defines mock behavior: when getUserEmail(1) is called, return 'user@example.com'Mock configured to return fixed email for userId 1-PASS
4Creates UserService instance with mock UserRepository injectedUserService ready with mock dependency-PASS
5Calls userService.getUserEmail(1)Method call routed to mock, returns 'user@example.com'Returned email equals 'user@example.com'PASS
6Verifies that mockRepo.getUserEmail(1) was called exactly onceMockito verifies interactionMock method getUserEmail(1) was called oncePASS
7Test ends successfullyAll assertions passed-PASS
Failure Scenario
Failing Condition: Mock method getUserEmail(1) not called or returns unexpected value
Execution Trace Quiz - 3 Questions
Test your understanding
What does the mock object simulate in this test?
AThe UserService class
BThe JUnit test runner
CThe UserRepository dependency
DThe assertEquals method
Key Result
Using mock objects helps isolate the unit under test by simulating dependencies, allowing focused and reliable testing of behavior without relying on real implementations.