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.
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:
- Create a Mock: Use Mockito's
mock()method to create a mock object. - Define Behavior: Use the
when(...).thenThrow(...)pattern to specify the behavior of the method. - 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:
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:
Multiple Exceptions
Mockito allows you to define multiple exceptions for a sequence of calls:
Table: Key Points for Mocking Exceptions
Here's a table summarizing key points when mocking exceptions with Mockito:
| Key Aspect | Description |
| Mock Object Creation | Use Mockito.mock(Class.class) to create a mock object. |
| Exception Definition | Use when(...).thenThrow(Exception.class) to define exception throwing. |
| Testing Framework Integration | Use frameworks like JUnit assertThrows() to assert exceptions. |
| Handling Checked Exceptions | Checked exceptions can be mocked in the same way as unchecked ones. |
| Sequence of Exceptions | Use 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
- Mockito how to verify method was called on an object created within a method?
- Mockito Inject real objects into private @Autowired fields
- Mockito InvalidUseOfMatchersException
- Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK
- Mockito List Matchers with generics
- Mockito match any class argument
- Mockito test a void method throws an exception
- Models passed to fit can only have training and the first argument in call as positional arguments, found

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseTrack 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.