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.
JUnit
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());
}
}
OutputSuccess
Important Notes
Always mock only the methods you need to test exceptions for.
Use assertThrows to check the exception type and message.
Summary
when().thenThrow() helps simulate errors in tests.
It is useful to check how your code handles exceptions.
Use it with assertThrows to verify the exception is thrown correctly.
Practice
(1/5)
1. What is the main purpose of using when().thenThrow() in JUnit tests?
easy
A. To verify that a method returns a specific value
B. To skip the execution of a test method
C. To create a new instance of a class
D. To simulate an exception being thrown by a mocked method
Solution
Step 1: Understand the role of when().thenThrow()
This syntax is used in mocking frameworks like Mockito to simulate exceptions when a mocked method is called.
Step 2: Identify the purpose in testing
It helps test how your code handles exceptions by forcing the mocked method to throw an exception.
Final Answer:
To simulate an exception being thrown by a mocked method -> Option D
Quick Check:
Exception simulation [OK]
Hint: Use when().thenThrow() to simulate errors in mocks [OK]
Common Mistakes:
Confusing exception simulation with return value mocking
Thinking it creates real exceptions instead of simulated ones
Using it to skip tests instead of throwing exceptions
2. Which of the following is the correct syntax to make a mocked method throw an IllegalArgumentException using Mockito?
easy
A. when(mock.method()).throwException(IllegalArgumentException)
B. when(mock.method()).thenThrow(new IllegalArgumentException())
C. mock.method().thenThrow(IllegalArgumentException)
D. when(mock.method()).throws(IllegalArgumentException)
Solution
Step 1: Recall Mockito syntax for throwing exceptions
The correct syntax uses when(mock.method()).thenThrow(new ExceptionType()).
Step 2: Match the options with correct syntax
when(mock.method()).thenThrow(new IllegalArgumentException()) matches the correct syntax exactly, creating a new exception instance inside thenThrow().
Final Answer:
when(mock.method()).thenThrow(new IllegalArgumentException()) -> Option B
Quick Check:
Correct Mockito exception syntax [OK]
Hint: Use thenThrow(new Exception()) with when() for exceptions [OK]
Common Mistakes:
Using throwException or throws which are not Mockito methods
Not creating a new exception instance
Calling thenThrow directly on mock.method()
3. Given the following code snippet, what will be the test result?
A. Missing try-catch block around mockService.getData()
B. assertThrows should not be used with exceptions
C. Incorrect use of thenThrow with exception class instead of instance
D. No error; code is correct
Solution
Step 1: Check thenThrow argument type
thenThrow requires an exception instance, not a class type.
Step 2: Identify correct usage
The code should use thenThrow(new RuntimeException()) instead of passing the class.
Final Answer:
Incorrect use of thenThrow with exception class instead of instance -> Option C
Quick Check:
thenThrow needs exception instance [OK]
Hint: Use new Exception() inside thenThrow(), not exception class [OK]
Common Mistakes:
Passing exception class instead of instance to thenThrow
Expecting assertThrows to catch exceptions without mocking
Adding unnecessary try-catch in test
5. You want to test that your service handles a NullPointerException thrown by a dependency's void call() method. Which of the following code snippets correctly mocks the dependency and verifies the exception handling using JUnit and Mockito?
hard
A. doThrow(new NullPointerException()).when(dependency).call();
assertThrows(NullPointerException.class, () -> service.callDependency());
B. when(dependency.call()).thenThrow(NullPointerException.class);
assertThrows(Exception.class, () -> service.callDependency());
C. when(dependency.call()).thenReturn(null);
assertThrows(NullPointerException.class, () -> service.callDependency());
D. when(dependency.call()).thenThrow(new NullPointerException());
assertThrows(NullPointerException.class, () -> service.callDependency());
Solution
Step 1: Understand mocking exceptions with void methods
If dependency.call() is a void method, doThrow().when() is the correct way to mock exceptions.
Step 2: Verify correct assertion
assertThrows(NullPointerException.class, () -> service.callDependency()) correctly checks that the service handles the exception.
Step 3: Analyze options
when(dependency.call()).thenThrow(new NullPointerException());
assertThrows(NullPointerException.class, () -> service.callDependency()); uses when().thenThrow() which works only for non-void methods. when(dependency.call()).thenThrow(NullPointerException.class);
assertThrows(Exception.class, () -> service.callDependency()); passes class instead of instance and wrong exception type in assertion. when(dependency.call()).thenReturn(null);
assertThrows(NullPointerException.class, () -> service.callDependency()); returns null instead of throwing exception.
Final Answer:
doThrow(new NullPointerException()).when(dependency).call();
assertThrows(NullPointerException.class, () -> service.callDependency()); -> Option A
Quick Check:
Use doThrow for void methods + assertThrows [OK]
Hint: Use doThrow() for void methods, then assertThrows() to check [OK]
Common Mistakes:
Using thenThrow() on void methods
Passing exception class instead of instance
Asserting wrong exception type
Returning null instead of throwing exception
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.