Test Overview
This test uses when().thenThrow() to simulate an exception from a mocked service method. It verifies that the exception is correctly thrown and handled.
This test uses when().thenThrow() to simulate an exception from a mocked service method. It verifies that the exception is correctly thrown and handled.
import static org.mockito.Mockito.*; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import org.mockito.Mockito; class UserService { UserRepository repo; UserService(UserRepository repo) { this.repo = repo; } public String getUserName(int id) { return repo.findNameById(id); } } interface UserRepository { String findNameById(int id); } public class UserServiceTest { @Test void testGetUserNameThrowsException() { UserRepository mockRepo = Mockito.mock(UserRepository.class); when(mockRepo.findNameById(1)).thenThrow(new RuntimeException("User not found")); UserService service = new UserService(mockRepo); RuntimeException thrown = assertThrows(RuntimeException.class, () -> { service.getUserName(1); }); assertEquals("User not found", thrown.getMessage()); } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Create mock of UserRepository | mockRepo is a mock object with no behavior yet | - | PASS |
| 2 | Stub mockRepo.findNameById(1) to throw RuntimeException("User not found") | mockRepo configured to throw exception when findNameById(1) is called | - | PASS |
| 3 | Create UserService instance with mockRepo | service uses mockRepo internally | - | PASS |
| 4 | Call service.getUserName(1) inside assertThrows | service calls mockRepo.findNameById(1), which throws RuntimeException | assertThrows verifies RuntimeException is thrown | PASS |
| 5 | Check exception message equals "User not found" | exception caught with message "User not found" | assertEquals verifies exception message | PASS |