Mockito
Java
Unit Testing
Exception Handling
Mocking

Mockito How to mock and assert a thrown exception?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Mockito is a popular mocking framework for unit tests in Java. It allows developers to create objects and define behaviors for dependencies of the class under test, without the need for complex setup. One of the crucial aspects of testing is verifying that exceptions are correctly thrown under specific conditions. This article discusses how to use Mockito for such scenarios effectively.

Understanding Mockito

Mockito is used to simulate the behavior of complex objects without instantiating them. This is particularly useful when you have dependencies that are time-consuming, resource-intensive, or simply unavailable during testing. By using Mockito, you can focus on the logic within the class under test.

Key Features of Mockito

  • Mock Object Creation: Easily create mock objects.
  • Defining Behaviors: Define return values for methods or throw exceptions.
  • Verification: Ensure that specific interactions have happened.
  • Argument Capturing: Capture arguments passed to mock methods for further assertions.

Mocking Exceptions in Mockito

When writing unit tests, you often need to test how code behaves when exceptions are thrown. Mockito provides an intuitive way to do this.

Basics of Throwing Exceptions with Mockito

To mock an exception with Mockito, you follow these general steps:

  1. Create a Mock: Use Mockito's mock() method to create a mock object.
  2. Define Behavior: Use the when(...).thenThrow(...) pattern to specify the behavior of the method.
  3. Execute and Assert: Execute the method under test and capture the exception using a testing framework like JUnit or TestNG.

Example Code

Below is an example illustrating these steps:

java
1import org.junit.jupiter.api.Test;
2import org.mockito.Mockito;
3import static org.mockito.Mockito.*;
4import static org.junit.jupiter.api.Assertions.*;
5
6class UserServiceTest {
7    @Test
8    void testThrowException() {
9        UserRepository userRepository = mock(UserRepository.class);
10        UserService userService = new UserService(userRepository);
11
12        when(userRepository.findByName("John")).thenThrow(new RuntimeException("User not found"));
13
14        Exception exception = assertThrows(RuntimeException.class, () -> {
15            userService.getUserByName("John");
16        });
17
18        assertEquals("User not found", exception.getMessage());
19    }
20}

In this example, the UserRepository mock object is configured to throw a RuntimeException when findByName("John") is invoked. The UserService then triggers this exception during the test, allowing you to verify that the system under test behaves as expected.

Advanced Exception Handling in Mockito

While the basic approach covers most cases, there are scenarios where more sophisticated exception handling is necessary.

Handling Checked Exceptions

Mockito can also be used to handle checked exceptions. You can specify checked exceptions using thenThrow in a similar manner. Here's an example:

java
import java.io.IOException;

when(mockedObject.someMethod()).thenThrow(new IOException("IO Error"));

Multiple Exceptions

Mockito allows you to define multiple exceptions for a sequence of calls:

java
when(mockedObject.someMethod())
    .thenThrow(new RuntimeException("First exception"))
    .thenThrow(new RuntimeException("Second exception"));

Table: Key Points for Mocking Exceptions

Here's a table summarizing key points when mocking exceptions with Mockito:

Key AspectDescription
Mock Object CreationUse Mockito.mock(Class.class) to create a mock object.
Exception DefinitionUse when(...).thenThrow(Exception.class) to define exception throwing.
Testing Framework IntegrationUse frameworks like JUnit assertThrows() to assert exceptions.
Handling Checked ExceptionsChecked exceptions can be mocked in the same way as unchecked ones.
Sequence of ExceptionsUse a sequence of thenThrow() calls for consecutive exceptions.

Conclusion

Mockito makes it easy to mock and assert exceptions, allowing you to create comprehensive unit tests that cover edge cases and error conditions. By integrating Mockito with a solid testing framework like JUnit, you can enhance the reliability and robustness of your Java applications. Understanding these techniques ensures that your code gracefully handles exceptions and meets high-quality standards.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.