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.
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.
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); }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts and MockitoExtension initializes the test class | UserServiceTest instance created with userRepository mocked | - | PASS |
| 2 | UserService instance created with mocked userRepository | UserService ready to use mocked dependency | - | PASS |
| 3 | Mock userRepository is stubbed to return 'Alice' when findNameById(1) is called | Mock behavior set | - | PASS |
| 4 | Call getUserName(1) on UserService | UserService calls mocked userRepository.findNameById(1) | - | PASS |
| 5 | Verify returned name is 'Alice' | Result from getUserName is 'Alice' | assertEquals("Alice", name) | PASS |
| 6 | Verify userRepository.findNameById(1) was called at least once | Mock interaction recorded | verify(userRepository).findNameById(1) | PASS |
| 7 | Test ends successfully | All assertions passed | - | PASS |