Verify void method invocation using Mockito
Preconditions (2)
✅ Expected Result: The void method is successfully mocked and verified to be called once without errors
import static org.mockito.Mockito.*; import org.junit.jupiter.api.Test; class Service { void performAction() { // some action } } public class ServiceTest { @Test void testPerformActionCalledOnce() { // Create mock Service mockService = mock(Service.class); // Stub void method to do nothing (optional, default is do nothing) doNothing().when(mockService).performAction(); // Call the void method mockService.performAction(); // Verify the method was called once verify(mockService, times(1)).performAction(); } }
The test imports Mockito static methods for easy mocking and verification.
We define a simple Service class with a void method performAction().
In the test method, we create a mock of Service using mock().
We stub the void method with doNothing() to explicitly show the approach, though Mockito does nothing by default for void methods.
We call the void method on the mock.
Finally, we verify that performAction() was called exactly once using verify() with times(1).
This ensures the void method was invoked as expected without side effects.
Now add data-driven testing to verify a void method is called multiple times with different mock objects
sendEmail() to do nothing when called?doNothing().when(mock).method() to mock void methods doing nothing.when() or verify().doThrow(new RuntimeException()).when(mock).deleteFile(); mock.deleteFile();
mock.deleteFile() is called?mock.deleteFile() triggers the RuntimeException as mocked.doNothing().when(mock.deleteFile());
doNothing().when(mock).method(), not passing method call inside when().logAction() was called exactly twice during a test. Which Mockito code correctly does this?verify(mock, times(n)).method() to check method called n times.Pass the test and this pattern moves unknown