0
0
JUnittesting~10 mins

Mocking void methods in JUnit - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test mocks a void method in a dependency to verify it is called correctly without executing its real behavior.

Test Code - JUnit 5 with Mockito
JUnit
import static org.mockito.Mockito.*;
import org.junit.jupiter.api.Test;

class Service {
    void performAction() {
        // Real implementation
    }
}

class Client {
    private final Service service;
    Client(Service service) {
        this.service = service;
    }
    void execute() {
        service.performAction();
    }
}

public class ClientTest {
    @Test
    void testExecute_callsPerformAction() {
        Service mockService = mock(Service.class);
        Client client = new Client(mockService);

        client.execute();

        verify(mockService).performAction();
    }
}
Execution Trace - 6 Steps
StepActionSystem StateAssertionResult
1Test startsJUnit test runner initialized-PASS
2Mockito creates a mock instance of ServiceService mock created with no real behavior-PASS
3Client instance created with mocked ServiceClient ready to use mockService-PASS
4Client.execute() is calledInside execute, service.performAction() is called on mock-PASS
5Mockito verifies performAction() was called on mockServiceVerification checks call history on mockServiceperformAction() was called exactly oncePASS
6Test ends successfullyNo exceptions thrown, all verifications passed-PASS
Failure Scenario
Failing Condition: performAction() was not called on the mockService during client.execute()
Execution Trace Quiz - 3 Questions
Test your understanding
What does the verify(mockService).performAction() line check?
AThat performAction() throws an exception
BThat performAction() returns a value
CThat performAction() was called on the mockService
DThat performAction() is a real method, not mocked
Key Result
Mocking void methods allows testing interactions without executing real code, ensuring the method is called as expected.