How to mock void methods in Mockito: a guide for beginners with examples

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Introduction: why are void methods a headache for beginners?

\n\n

Have you ever written a unit test in Java with Mockito and suddenly hit a wall? Everything seems simple: you mock an object, configure behavior for methods that return something (a string, a number, a list). But as soon as you get to void methods — those that return nothing, but only do something internally (for example, save data, send an email, log an action) — you get stuck.

\n\n

Why? Because the familiar when(mock.someMethod()).thenReturn(something) doesn't work here. The compiler simply won't let you write when(mock.voidMethod()).thenReturn(...) — a void method returns nothing, and thenReturn is meaningless here.

\n\n

It is precisely this question — "How to mock void methods with Mockito" — that has garnered thousands of views on Stack Overflow. And today we will cover it once and for all. You will learn not just how to mock void methods, but how to do it correctly, cleanly, and without pain.

\n\n

Let's go! 🚀

\n\n

What is a void method from a testing perspective?

\n\n

A void method is a method that performs an action but does not return a result. For example:

\n\n
public class EmailService {\n    public void sendWelcomeEmail(String email) {\n        // actual email sending here\n        System.out.println("Sending email to " + email);\n    }\n}
\n\n

In a real project, we don't want to actually send an email every time we run a test. We simply need to verify that the method was called, or stub its execution, or make it throw an exception (to test error handling).

\n\n

For this, Mockito provides a special syntax using doNothing(), doThrow(), doAnswer(), and doCallRealMethod().

\n\n

1. The most common case: doNothing() — simply stub a void method

\n\n

If you need a void method to do nothing when called — use doNothing(). This is Mockito's default behavior for void methods, but sometimes it's useful to specify it explicitly (for example, for readability or when using a spy).

\n\n
import org.junit.jupiter.api.Test;\nimport org.junit.jupiter.api.extension.ExtendWith;\nimport org.mockito.Mock;\nimport org.mockito.junit.jupiter.MockitoExtension;\n\nimport static org.mockito.Mockito.*;\n\n@ExtendWith(MockitoExtension.class)\npublic class EmailServiceTest {\n\n    @Mock\n    private EmailService emailService;\n\n    @Test\n    void testDoNothing() {\n        // Configure: do nothing when sendWelcomeEmail is called\n        doNothing().when(emailService).sendWelcomeEmail(anyString());\n\n        // Call the method\n        emailService.sendWelcomeEmail("test@example.com");\n\n        // Verify that the method was actually called\n        verify(emailService).sendWelcomeEmail("test@example.com");\n    }\n}
\n\n

Important: If you use @Mock, you don't need to write doNothing() — Mockito makes void methods "dummies" by default. But if you use @Spy, the real method will be called, and doNothing() is needed to prevent that.

\n\n

2. doThrow() — simulate an error in a void method

\n\n

A very common task: to check how your code reacts if the email sending service fails with an error. To do this, we make the void method throw an exception.

\n\n
@Test\nvoid testDoThrow() {\n    // Configure: throw RuntimeException when sendWelcomeEmail is called\n    doThrow(new RuntimeException("Email sending error"))\n            .when(emailService).sendWelcomeEmail(anyString());\n\n    // Now calling the method will throw an exception\n    assertThrows(RuntimeException.class, () -> {\n        emailService.sendWelcomeEmail("fail@example.com");\n    });\n\n                

Blogs

Book Recommendations