0
0
JUnittesting~15 mins

Mocking void methods in JUnit - Build an Automation Script

Choose your learning style9 modes available
Verify void method invocation using Mockito
Preconditions (2)
Step 1: Create a mock of the class containing the void method
Step 2: Stub the void method to do nothing or throw an exception if needed
Step 3: Call the void method on the mock object
Step 4: Verify that the void method was called exactly once
✅ Expected Result: The void method is successfully mocked and verified to be called once without errors
Automation Requirements - JUnit 5 with Mockito
Assertions Needed:
Verify void method invocation count using Mockito.verify()
Best Practices:
Use Mockito.mock() to create mock objects
Use Mockito.doNothing() or Mockito.doThrow() for stubbing void methods
Use Mockito.verify() to check method calls
Keep test methods small and focused
Automated Solution
JUnit
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.

Common Mistakes - 3 Pitfalls
Using when().thenReturn() to stub void methods
Not verifying the void method call
Calling real method on mock instead of stubbed method
Bonus Challenge

Now add data-driven testing to verify a void method is called multiple times with different mock objects

Show Hint