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

How to Fix: Mockito test a void method throws an exception

Test void method with exceptions using Mockito Stubber

Quick Answer: Use the `doThrow` method on a stubbed object, specifying the exception type and value.

You are getting this error because Mockito's `when` method does not support stubbing void methods directly. This is due to the fact that a void method cannot return a value, so there is no way for Mockito to verify if the method was called or not.

🛠️ Step-by-Step Verified Fixes

Method 1: Use a Void Method That Throws an Exception

  1. Step 1: Create a void method that throws the exception you want to test for.

Method 2: Use Mockito's `whenThrowing` Method

  1. Step 1: Create a stubber for the method you want to test.
  2. Step 2: Use Mockito's `whenThrowing` method to specify the exception that should be thrown.

✨ Wrapping Up

By following these steps, you can successfully test if a void method throws an exception using Mockito.

Did this fix your problem?

If not, try searching for specific error codes.

🔍 Search Error Database

❓ Frequently Asked Questions