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.
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.
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); } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | JUnit test runner initialized | - | PASS |
| 2 | Mockito creates a mock object for Dependency interface | Mock object ready to simulate Dependency | - | PASS |
| 3 | Stub getData() method of mock to return 'mocked data' | Mock configured to return controlled value | - | PASS |
| 4 | Create Service instance with mocked Dependency | Service uses mock instead of real Dependency | - | PASS |
| 5 | Call serve() method on Service instance | Service calls mock's getData() method | Check that serve() returns 'Service calls mocked data' | PASS |
| 6 | Test ends | Test completed successfully | - | PASS |