Mockito thenThrow()

1. Overview

Mockito doesn't just allow developers to mock return values but also to simulate exceptions or errors that might occur during real executions. The thenThrow() method is particularly useful in this regard. This tutorial dives into how one can employ the thenThrow() method to mock exceptions and test error scenarios.

2. Development Steps

1. Set up a new Maven project.

2. Integrate the necessary dependencies: JUnit 5 and Mockito.

3. Construct a class having a method that can potentially throw an exception.

4. Design a test class for the previously created class.

5. Utilize the thenThrow() method to simulate an exception in the mocked method.

6. Formulate and execute a test case.

7. Analyze the test results.

3. Dependencies (Mockito and JUnit 5)

<!-- JUnit 5 -->
<!-- Mockito -->

4. Code Program

// Step 3: Create the DatabaseService class
class DatabaseService {
    String fetchData(String query) throws Exception {
        // Typically, this method might fetch data from a database
        return "Data";
// Step 4 and 5: Frame a test class for DatabaseService
import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class DatabaseServiceTest {
    public void fetchDataTest() {
        // Generate a mock of DatabaseService
        DatabaseService mockService = mock(DatabaseService.class);
        // Use the thenThrow() method to simulate an exception
        when(mockService.fetchData("errorQuery")).thenThrow(new Exception("Database Error"));
        // Assert that the exception is thrown
        assertThrows(Exception.class, () -> mockService.fetchData("errorQuery"));


The fetchDataTest will pass successfully, asserting that the thenThrow() method accurately simulated the exception scenario for the mocked DatabaseService.

Code Explanation:

1. With Mockito and JUnit 5 integrated, we initiated a simple DatabaseService class that contains a fetchData method. This method, under genuine conditions, might communicate with a database.

2. In the test suite, a mock of the DatabaseService was created using the mock() function of Mockito.

3. To emulate an exception, we used the thenThrow() method. Specifically, we indicated that when the fetchData method of our mock is invoked with "errorQuery" as the parameter, it should throw a new Exception with the message "Database Error".

4. Subsequently, we wrote a test to verify that this exception is indeed thrown when the fetchData method is called with the designated parameter.

5. Conclusion

Mockito's thenThrow() method is an essential tool for developers aiming to test exception scenarios in their code. By facilitating the simulation of errors and exceptions, it ensures that the software remains robust and gracefully handles all kinds of edge cases. Adopting thenThrow() in unit tests ensures comprehensive coverage and readiness for real-world challenges.

Related Mockito Methods

Mockito mock()
Mockito spy()
Mockito when()
Mockito thenThrow()
Mockito verify()
Mockito times()
Mockito never()
Mockito any()
Mockito eq()
Mockito inOrder()
Mockito doReturn()
Mockito doThrow()
Mockito doAnswer()
Mockito timeout()
Mockito ArgumentMatchers