0
0
JunitHow-ToBeginner ยท 3 min read

How to Mock Void Method in Mockito with JUnit

To mock a void method in Mockito with JUnit, use doNothing(), doThrow(), or doAnswer() with when() on the mocked object. This allows you to define behavior for methods that return nothing and verify interactions without errors.
๐Ÿ“

Syntax

Use doNothing() to mock a void method that does nothing, doThrow() to simulate exceptions, and doAnswer() for custom behavior. These are chained with when(mockObject).voidMethod(args).

  • doNothing(): Ignores the void method call.
  • doThrow(): Throws an exception when the void method is called.
  • doAnswer(): Executes custom code when the void method is called.
java
doNothing().when(mockObject).voidMethod(args);
doThrow(new Exception()).when(mockObject).voidMethod(args);
doAnswer(invocation -> { /* custom code */ return null; }).when(mockObject).voidMethod(args);
๐Ÿ’ป

Example

This example shows how to mock a void method clear() of a mocked List object using doNothing(). It verifies that the method was called once without throwing exceptions.

java
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;

import java.util.List;

import org.junit.jupiter.api.Test;

public class VoidMethodMockTest {

    @Test
    void testMockVoidMethod() {
        List<String> mockedList = mock(List.class);

        // Mock void method clear() to do nothing
        doNothing().when(mockedList).clear();

        // Call the void method
        mockedList.clear();

        // Verify clear() was called once
        verify(mockedList, times(1)).clear();
    }
}
Output
Test passed with no exceptions.
โš ๏ธ

Common Pitfalls

One common mistake is trying to use when() directly with void methods like when(mock.voidMethod()).thenReturn(), which causes errors because void methods do not return values. Always use doNothing(), doThrow(), or doAnswer() with when() for void methods.

java
/* Wrong way - causes error */
// when(mockedList.clear()).thenReturn(null); // This will not compile

/* Right way */
doNothing().when(mockedList).clear();
๐Ÿ“Š

Quick Reference

MethodPurposeUsage Example
doNothing()Ignore void method calldoNothing().when(mock).voidMethod();
doThrow()Throw exception on void method calldoThrow(new Exception()).when(mock).voidMethod();
doAnswer()Custom behavior on void method calldoAnswer(invocation -> { /* code */ return null; }).when(mock).voidMethod();
โœ…

Key Takeaways

Use doNothing(), doThrow(), or doAnswer() with when() to mock void methods in Mockito.
Never use when() directly on void methods as they do not return values.
Verify void method calls with verify(mock, times(n)).voidMethod() to check interactions.
doThrow() helps simulate exceptions for testing error handling in void methods.
doAnswer() allows custom code execution when the void method is called.