0
0
JUnittesting~10 mins

Why mocking isolates units under test in JUnit - Test Execution Impact

Choose your learning style9 modes available
Test Overview

This test checks how mocking helps isolate a unit by replacing its dependencies with mocks. It verifies that the unit behaves correctly when its dependency returns a controlled value.

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

class Service {
    private final Dependency dependency;
    Service(Dependency dependency) {
        this.dependency = dependency;
    }
    String serve() {
        return "Service calls " + dependency.getData();
    }
}

interface Dependency {
    String getData();
}

public class ServiceTest {
    @Test
    void testServeWithMockedDependency() {
        Dependency mockDep = mock(Dependency.class);
        when(mockDep.getData()).thenReturn("mocked data");

        Service service = new Service(mockDep);
        String result = service.serve();

        assertEquals("Service calls mocked data", result);
    }
}
Execution Trace - 6 Steps
StepActionSystem StateAssertionResult
1Test startsJUnit test runner initialized-PASS
2Mockito creates a mock object for Dependency interfaceMock object ready to simulate Dependency-PASS
3Stub getData() method of mock to return 'mocked data'Mock configured to return controlled value-PASS
4Create Service instance with mocked DependencyService uses mock instead of real Dependency-PASS
5Call serve() method on Service instanceService calls mock's getData() methodCheck that serve() returns 'Service calls mocked data'PASS
6Test endsTest completed successfully-PASS
Failure Scenario
Failing Condition: Mock not configured correctly or returns unexpected value
Execution Trace Quiz - 3 Questions
Test your understanding
What is the main purpose of mocking in this test?
ATo test the real Dependency implementation
BTo replace the real dependency with a controlled fake
CTo speed up the Service method
DTo avoid writing assertions
Key Result
Mocking isolates the unit under test by replacing real dependencies with controlled mocks, allowing focused testing of the unit's behavior without side effects or external dependencies.