W3docs

How to mock void methods with Mockito

To mock a void method with Mockito, you can use the doAnswer method. Here is an example of how you can use it:

To mock a void method with Mockito, you can use the doAnswer method. Here is an example of how you can use it:


import static org.mockito.Mockito.*;
import static org.mockito.ArgumentMatchers.*;

// Create a mock of the class that has the void method you want to mock
MyClass mock = mock(MyClass.class);

// Use doAnswer with a lambda to specify behavior when the void method is called
doAnswer(invocation -> {
  // Access arguments passed to the method
  Object[] args = invocation.getArguments();
  // Access the mock object itself
  MyClass mockObj = invocation.getMock();
  // Return null to do nothing, or add side effects/custom logic here
  return null;
}).when(mock).voidMethod(anyInt(), anyString());

This will cause the voidMethod to do nothing when it is called, but you can customize the behavior by adding side effects or other logic inside the lambda. Returning null explicitly keeps the method as a no-op.

Note that doAnswer returns a Stubber, so you need to use the when method to specify which method you want to stub. You can also use doNothing if you just want the method to do nothing when it is called.

Note: This example uses modern Mockito syntax (Mockito 4+). Older versions relied on the deprecated InvocationOnMock interface and anonymous Answer classes.

I hope this helps! Let me know if you have any questions.