This test creates a fake UserRepository that throws an exception when findById(1) is called. The test checks that getUser(1) throws the same exception with the correct message.
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
class UserService {
UserRepository repo;
UserService(UserRepository repo) {
this.repo = repo;
}
User getUser(int id) {
return repo.findById(id);
}
}
interface UserRepository {
User findById(int id);
}
class User {}
public class UserServiceTest {
@Test
void testGetUserThrowsException() {
UserRepository mockRepo = mock(UserRepository.class);
when(mockRepo.findById(1)).thenThrow(new RuntimeException("User not found"));
UserService service = new UserService(mockRepo);
RuntimeException thrown = assertThrows(RuntimeException.class, () -> {
service.getUser(1);
});
assertEquals("User not found", thrown.getMessage());
}
}