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.
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.
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); } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | JUnit test runner initialized | - | PASS |
| 2 | Creates mock object for UserRepository using Mockito.mock() | Mock UserRepository instance created | - | PASS |
| 3 | Defines mock behavior: when getUserEmail(1) is called, return 'user@example.com' | Mock configured to return fixed email for userId 1 | - | PASS |
| 4 | Creates UserService instance with mock UserRepository injected | UserService ready with mock dependency | - | PASS |
| 5 | Calls userService.getUserEmail(1) | Method call routed to mock, returns 'user@example.com' | Returned email equals 'user@example.com' | PASS |
| 6 | Verifies that mockRepo.getUserEmail(1) was called exactly once | Mockito verifies interaction | Mock method getUserEmail(1) was called once | PASS |
| 7 | Test ends successfully | All assertions passed | - | PASS |