Coding⏱️ 2 min read📅 2026-05-31

How to Fix: Mockito How to mock and assert a thrown exception?

Learn how to mock and assert a thrown exception with Mockito in JUnit tests.

Quick Answer: Use `when()` to throw an exception, then use `assertThrows()` or `verify()` to check the type of exception thrown.

Mockito is a popular mocking library for Java, and when it comes to testing exceptions, it can be a bit tricky. In this article, we'll explore how to mock and assert a thrown exception using Mockito in a JUnit test.

🔍 Why This Happens

  • When you're testing an exception, you want to ensure that the correct exception is thrown and caught. However, Mockito's default behavior is to not throw exceptions.

🛠️ Step-by-Step Verified Fixes

Method 1: Using Mockito's when() method with an exception

  1. Step 1: Use the `when()` method to specify that a certain method should throw an exception.

Method 2: Using Mockito's when() method with a custom exception

  1. Step 1: Create a custom exception that extends the `Exception` class.

🎯 Final Words

By following these steps, you can mock and assert a thrown exception using Mockito in your JUnit test. Remember to always verify that the correct exception is thrown and caught.

Did this fix your problem?

If not, try searching for specific error codes.

🔍 Search Error Database

❓ Frequently Asked Questions