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 |
Mocking helps to:mock() with the class type as argument.Mockito.mock(MyClass.class);class ServiceTest {
@Mock
Repository repo;
@InjectMocks
Service service;
@Test
void testGetData() {
when(repo.getData()).thenReturn("mocked data");
String result = service.getData();
assertEquals("mocked data", result);
}
}Repository is not connected to a database?repo is mocked to return "mocked data" when getData() is called.repo is a mock that returns controlled data -> Option A@Test
void testCalculate() {
Calculator calc = Mockito.mock(Calculator.class);
when(calc.add(2, 3)).thenReturn(5);
int result = calc.add(2, 3);
assertEquals(6, result);
}add(2, 3) is called.Pass the test and this pattern moves unknown