Mocking Void Methods with Mockito: A Complete Step‑by‑Step Guide

This article explains how to use Mockito's doNothing, doAnswer, doThrow, and doCallRealMethod to mock void methods in Java, demonstrating parameter verification, argument capture, and real‑method invocation with detailed code examples and reasoning behind each approach.

FunTester
FunTester
FunTester
Mocking Void Methods with Mockito: A Complete Step‑by‑Step Guide

When a method returns void, the usual when(...).thenReturn(...) pattern cannot be applied, so Mockito provides a set of doXxx() methods to control the behavior of void calls.

Example scenario

Consider a UserService class that delegates to a userRepository:

public class UserService {
    public void updateName(Long id, String name) {
        userRepository.updateName(id, name);
    }
}

The test needs to verify that userRepository.updateName is called with the correct arguments.

Using doNothing()

doNothing()

is the default behavior for void methods; it simply ignores the call. It is useful when the test only cares about verification:

@Test
public void test001() {
    doNothing().when(mockedUserRepository).updateName(anyLong(), anyString());
    userService.updateName(1L, "FunTester");
    verify(mockedUserRepository, times(1)).updateName(1L, "FunTester");
}

If the method body is empty, the explicit doNothing() call can be omitted because Mockito already does nothing.

Capturing arguments with doNothing()

To capture the arguments passed to the void method, combine doNothing() with ArgumentCaptor:

@Test
public void testUpdateNameUsingArgumentCaptor() {
    ArgumentCaptor<Long> idCapture = ArgumentCaptor.forClass(Long.class);
    ArgumentCaptor<String> nameCapture = ArgumentCaptor.forClass(String.class);
    doNothing().when(mockedUserRepository).updateName(idCapture.capture(), nameCapture.capture());
    userService.updateName(1L, "FunTester");
    assertEquals(1L, idCapture.getValue());
    assertEquals("FunTester", nameCapture.getValue());
}

Using doAnswer() for custom logic

doAnswer()

lets the test execute arbitrary code when the void method is invoked, which is handy for logging or additional assertions:

@Test
public void testUpdateNameUsingDoAnswer() {
    doAnswer(invocation -> {
        long id = invocation.getArgument(0);
        String name = invocation.getArgument(1);
        System.out.println("called for id: " + id + " and name: " + name);
        assertEquals(1L, id);
        assertEquals("FunTester", name);
        return null;
    }).when(mockedUserRepository).updateName(anyLong(), anyString());
    userService.updateName(1L, "FunTester");
    verify(mockedUserRepository, times(1)).updateName(1L, "FunTester");
}

Using doThrow() to simulate exceptions

When the test must ensure that a void method throws an exception under certain conditions, doThrow() is used:

@Test(expected = InvalidParamException.class)
public void testUpdateNameThrowExceptionWhenIdNull() {
    doThrow(new InvalidParamException())
        .when(mockedUserRepository).updateName(null, anyString());
    userService.updateName(null, "FunTester");
}

Calling the real method with doCallRealMethod()

If the test needs the actual implementation of the void method while still using a mock for other interactions, doCallRealMethod() forces the real method execution:

@Test
public void testUpdateNameCallRealRepositoryMethod() {
    doCallRealMethod().when(mockedUserRepository).updateName(anyLong(), anyString());
    userService.updateName(1L, "真实调用方法");
    verify(mockedUserRepository, times(1)).add(1L, "真实调用方法");
}

Each doXxx() variant addresses a specific testing need: ignoring the call, injecting custom behavior, throwing exceptions, or delegating to the real implementation. By selecting the appropriate method, developers can precisely verify interactions with void methods while keeping tests readable and maintainable.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Javaunit testingMockingJUnitMockitoVoid Methods
FunTester
Written by

FunTester

10k followers, 1k articles | completely useless

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.