Testing Your Spring Boot Application
Java & Spring Boot for Beginners · Part 12 of 14
- #Java
- #Spring Boot
- #Beginners
- #testing
- #junit
- #mockito
At the end of Part 11 I made a claim: the API rejects bad input with a clean
400, a missing task comes back as a 404, and nothing leaks a stack trace.
You tried it with curl and it worked. Good. Now change one line in the
service next week and tell me whether it still works.
You can't, not without running curl again by hand. Then again after the
next change, and the one after that. Tests exist so you stop doing that. They
let you change code without holding your breath.
This part adds three kinds of tests to the task API we've been building since Part 9. Each one answers a different question, and knowing which question you're asking matters more than any annotation.
What's already on your classpath
If you generated the project with Spring Initializr, you already have
spring-boot-starter-test. It pulls in everything this post uses:
- JUnit 5 (Jupiter): the test runner,
@Test, and assertions. - Mockito: builds fake versions of your dependencies.
- AssertJ: readable assertions like
assertThat(x).isEqualTo(y). - Spring Test / MockMvc: calls your controllers without starting a real server.
Tests live under src/test/java, mirroring your package structure. Run them
with ./mvnw test or ./gradlew test, or with the green arrow next to a
test in your IDE.
For reference, here's the slice of the project we're testing. It's the service and controller as they stood at the end of Part 11:
@Service
public class TaskService {
private final TaskRepository taskRepository;
public TaskService(TaskRepository taskRepository) {
this.taskRepository = taskRepository;
}
public Task getTask(Long id) {
return taskRepository.findById(id)
.orElseThrow(() -> new TaskNotFoundException(id));
}
public Task createTask(CreateTaskRequest request) {
Task task = new Task();
task.setTitle(request.title());
task.setDescription(request.description());
task.setDueDate(request.dueDate());
return taskRepository.save(task);
}
}
The controller is a thin layer on top: GET /api/tasks/{id} calls
getTask, and POST /api/tasks takes a @Valid CreateTaskRequest and
calls createTask.
Three kinds of tests, three different questions
Before writing anything, it helps to see the options side by side:
- A unit test asks: does this one class do the right thing, assuming everything it talks to behaves?
- A slice test asks: does the web layer translate HTTP into method calls and back, correctly, including validation and error handling?
- An integration test asks: when everything is actually wired together, does a request make it from the front door to the database and back?
You want lots of the first, some of the second, and a few of the third. The reason is speed. Unit tests run in milliseconds, so you'll run them constantly. Integration tests start the whole application, so each one costs seconds and you'll run them less often.
Unit testing the service with Mockito
TaskService depends on TaskRepository. In a unit test we don't want a
database. We want to say "pretend the repository returns this" and check
what the service does with it. That's what Mockito is for.
@ExtendWith(MockitoExtension.class)
class TaskServiceTest {
@Mock
private TaskRepository taskRepository;
@InjectMocks
private TaskService taskService;
@Test
void getTask_returnsTask_whenItExists() {
Task task = new Task();
task.setId(1L);
task.setTitle("Write tests");
when(taskRepository.findById(1L)).thenReturn(Optional.of(task));
Task result = taskService.getTask(1L);
assertThat(result.getTitle()).isEqualTo("Write tests");
}
@Test
void getTask_throwsNotFound_whenItDoesNotExist() {
when(taskRepository.findById(99L)).thenReturn(Optional.empty());
assertThatThrownBy(() -> taskService.getTask(99L))
.isInstanceOf(TaskNotFoundException.class)
.hasMessageContaining("99");
}
@Test
void createTask_copiesFieldsAndSaves() {
var request = new CreateTaskRequest("Ship it", "Part 12", LocalDate.now());
when(taskRepository.save(any(Task.class))).thenAnswer(inv -> inv.getArgument(0));
Task result = taskService.createTask(request);
assertThat(result.getTitle()).isEqualTo("Ship it");
verify(taskRepository).save(any(Task.class));
}
}
A few things going on here:
@ExtendWith(MockitoExtension.class)switches Mockito on. No Spring context starts, which is why this runs so fast.@Mockcreates a fakeTaskRepository. By default every method returns an "empty" value (null,Optional.empty(), an empty list) until you tell it otherwise.@InjectMocksbuilds a realTaskServiceand passes the mock into its constructor.when(...).thenReturn(...)is the "pretend" part.verify(...)checks that a call actually happened.
Every test follows the same three beats: arrange (set up the mock), act (call the method), assert (check the result). The blank lines in each test are there on purpose. Once you're used to that rhythm, you can read any test in a few seconds.
Notice the second test. It checks the failure path, and that's the one people tend to skip. Part 11 was all about failure paths, so they deserve tests as much as the happy path does.
Slice testing the controller with @WebMvcTest
The service is covered, but the service test says nothing about HTTP. Does
POST /api/tasks with an empty title really return 400? Does a missing
task really come back as 404 with a ProblemDetail body? Those behaviors
live in the controller, in @Valid, and in the @RestControllerAdvice. A
unit test can't reach them.
@WebMvcTest starts a slice of Spring: controllers, advice classes, JSON
conversion and validation. It leaves out services, repositories and the
database. You provide the service as a mock.
@WebMvcTest(TaskController.class)
class TaskControllerTest {
@Autowired
private MockMvc mockMvc;
@MockitoBean
private TaskService taskService;
@Test
void getTask_returns200WithBody() throws Exception {
Task task = new Task();
task.setId(1L);
task.setTitle("Write tests");
when(taskService.getTask(1L)).thenReturn(task);
mockMvc.perform(get("/api/tasks/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.title").value("Write tests"));
}
@Test
void getTask_returns404_whenMissing() throws Exception {
when(taskService.getTask(99L)).thenThrow(new TaskNotFoundException(99L));
mockMvc.perform(get("/api/tasks/99"))
.andExpect(status().isNotFound())
.andExpect(jsonPath("$.title").value("Task not found"));
}
@Test
void createTask_returns400_whenTitleIsBlank() throws Exception {
mockMvc.perform(post("/api/tasks")
.contentType(MediaType.APPLICATION_JSON)
.content("""
{ "title": "", "dueDate": "2099-01-01" }
"""))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.errors[0].field").value("title"));
verifyNoInteractions(taskService);
}
}
MockMvc sends fake HTTP requests through the real Spring MVC machinery. No
port gets opened, but your annotations, validation and exception handler all
run exactly as they would in production.
The last line of the third test, verifyNoInteractions(taskService), is
where the test earns its keep. It proves the invalid request never reached
the service, which was the whole promise of @Valid in Part 11. If someone
removes that annotation by accident, this test goes red.
About @MockitoBean: it arrived in Spring Boot 3.4 and replaces the older
@MockBean, which is now deprecated. If you're on an earlier 3.x version,
use @MockBean and everything else stays the same. Either way it does the
same job as @Mock, except the mock gets registered as a Spring bean so the
controller can have it injected.
One integration test with @SpringBootTest
Every test so far used mocks somewhere. That's fine, but mocks can lie. They return whatever you told them to, even when the real code would do something else. So you want at least one test with no mocks at all, where a real request hits a real controller, a real service, a real repository and the H2 database from Part 10.
@SpringBootTest
@AutoConfigureMockMvc
class TaskApiIntegrationTest {
@Autowired
private MockMvc mockMvc;
@Test
void createThenFetchTask() throws Exception {
String location = mockMvc.perform(post("/api/tasks")
.contentType(MediaType.APPLICATION_JSON)
.content("""
{ "title": "End to end", "dueDate": "2099-01-01" }
"""))
.andExpect(status().isCreated())
.andReturn().getResponse().getHeader("Location");
mockMvc.perform(get(location))
.andExpect(status().isOk())
.andExpect(jsonPath("$.title").value("End to end"));
}
}
@SpringBootTest starts the whole application context, the same one
main() would start. @AutoConfigureMockMvc gives you the same MockMvc
API as before, so the test reads the same way. This one test covers the
wiring, the JPA mapping, the H2 config and the JSON round trip, all in one go.
It is also the slowest test in the project by a wide margin, and that's the trade-off. Write a handful of these for your most important flows and let the fast tests handle the edge cases.
(If your POST returns 201 without a Location header, as the Part 9
version did, grab the id from the response body with jsonPath instead.
Adding the header is the more RESTful choice, though, and a nice small
exercise.)
What to test, and what to skip
This is where beginners burn the most time, usually by testing too much of the wrong thing:
Test your decisions. Any place your code makes a choice (an if, a
thrown exception, a validation rule, a calculation) is a place where it can
choose wrong. That's what tests are for.
Don't test the framework. You don't need a test proving
taskRepository.save() saves. Spring Data's own test suite already covers
that far more thoroughly than you will. Getters and setters are the same
story. A test that can only fail when the JDK is broken tells you nothing.
Test behavior, not implementation. Go through the public method, not the private helpers behind it. If you refactor the internals and the behavior stays the same, the tests should stay green. When tests break on every refactor, people start deleting them instead of fixing them.
Don't chase a coverage number. Coverage tells you which lines ran, not whether anything checked the result. A test with no assertions can still hit 100%. Use coverage to find code nobody tested, and don't treat it as a score.
A quick word on naming
You'll see a lot of conventions out there. methodName_expectedResult_condition,
like in the examples above, is plain and it works. When a test fails in CI
six months from now, the name is the first thing someone reads. Something
like createTask_returns400_whenTitleIsBlank tells them what broke before
they open the file. A name like test3 tells them nothing.
What's next
The project now has tests at three levels: fast unit tests for the logic, slice tests for the HTTP contract, and one integration test that proves the pieces fit. You can change code and find out within seconds whether you broke something.
There's one gap left, and it's a big one: anyone who can reach the API can create, change and delete every task in it. Part 13: Securing Your API fixes that with Spring Security, adding authentication and authorization to these same endpoints. And since the tests you just wrote will need to log in too, you'll see how to test secured endpoints as well.