0
0
JUnittesting~5 mins

Mocking void methods in JUnit

Choose your learning style9 modes available
Introduction

Sometimes, methods do not return any value but still perform important actions. Mocking void methods helps us test code that depends on these actions without running the real method.

When a method changes data or state but returns nothing
When a method sends messages or logs information
When a method calls external systems but you want to avoid real calls
When you want to check if a void method was called correctly
When you want to simulate exceptions thrown by void methods
Syntax
JUnit
doNothing().when(mockObject).voidMethod();
doThrow(new Exception()).when(mockObject).voidMethod();

Use doNothing() to skip the real void method.

Use doThrow() to simulate exceptions from void methods.

Examples
This tells the mock list to do nothing when clear() is called.
JUnit
doNothing().when(mockList).clear();
This makes the mock service throw an exception when process() is called.
JUnit
doThrow(new RuntimeException()).when(mockService).process();
Sample Program

This test mocks a List object. It makes clear() do nothing and verifies it was called once. It also makes add("test") throw an exception and prints the exception message.

JUnit
import static org.mockito.Mockito.*;
import org.junit.jupiter.api.Test;
import java.util.List;

public class VoidMethodMockTest {

    @Test
    void testVoidMethodMocking() {
        List<String> mockList = mock(List.class);

        // Mock clear() to do nothing
        doNothing().when(mockList).clear();

        // Call clear()
        mockList.clear();

        // Verify clear() was called once
        verify(mockList, times(1)).clear();

        // Mock add() to throw exception
        doThrow(new RuntimeException("Add failed")).when(mockList).add("test");

        try {
            mockList.add("test");
        } catch (RuntimeException e) {
            System.out.println(e.getMessage());
        }
    }
}
OutputSuccess
Important Notes

Always verify that the void method was called if that matters for your test.

Use doAnswer() if you want to run custom code when the void method is called.

Summary

Void methods do not return values but can be mocked using doNothing() or doThrow().

Mocking void methods helps test code without running real side effects.

Always verify calls to void methods if your test depends on them.