Testing a Service
A service test is a plain unit test that calls the real service directly. It needs no Spring context, so it runs fast and stays simple.
Make the fake repository
This line makes a fake repository. It answers only what the test tells it to.
TaskRepository repository = mock(TaskRepository.class);Build the real service
This line builds the real service with the fake repository. No Spring context starts.
TaskService service = new TaskService(repository);Check the open count
This line checks that two unfinished tasks come back. Two of the three seed tasks are open.
assertEquals(2, service.openTasks().size());Example
package com.example.demo;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class TaskServiceTest {
@Test
void openTasksCountsUnfinishedTasks() {
TaskRepository repository = mock(TaskRepository.class);
when(repository.findAll()).thenReturn(List.of(
new Task("Buy milk", false),
new Task("Ship Spring Boot", true),
new Task("Read a book", false)));
TaskService service = new TaskService(repository);
assertEquals(2, service.openTasks().size());
}
}Key points
- A unit test checks one small piece on its own.
- The real service runs with a fake repository.
- A fake repository returns set answers for the test.
- No Spring annotation starts a context in this test.
- Plain tests run fast because nothing extra starts.
In this example, the mock call makes a fake repository. The when line tells the fake to return the three seed tasks. The real TaskService is built with that fake. The test calls openTasks on the real service. The assertEquals call checks that two unfinished tasks come back. The test run reports one test run with no failures.
Note
Test the service logic, not the Spring wiring.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What runs in a plain service test?