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 |
mock objects in JUnit testing?mock(Class.class) to create mock objects.MyClass mock = mock(MyClass.class);result be after execution?List<String> mockList = mock(List.class); when(mockList.size()).thenReturn(5); int result = mockList.size();
size() method is stubbed to return 5 when called.mockList.size() returns 5 as per the stub, not the real list size.MyService service = mock(MyService.class);
when(service.getData()).thenReturn("data");
verify(service).getData();service.getData() before verify, so verification fails.service.getData() before verify -> Option DgetValue()?thenReturn() calls to specify sequential return values.when(mock.getValue()).thenReturn("first").thenReturn("second"); matches the correct chaining syntax for sequential calls.Pass the test and this pattern moves unknown