Testing One Controller
@WebMvcTest is a test slice that starts one controller without the rest of the app. It loads only the web layer, so the test runs fast.
Test one controller
This mark starts only TaskController and its web parts. The rest of the app stays out.
@WebMvcTest(TaskController.class)
class TaskControllerWebTest {
}Fake the service
This field is a fake TaskService. Spring fills it in for the test.
@MockitoBean
private TaskService taskService;Tell the fake what to return
This line tells the fake service to return an empty list. The controller then has tasks to show.
when(taskService.findAll()).thenReturn(List.of());Example
package com.example.demo;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest;
import org.springframework.test.web.servlet.MockMvc;
import java.util.List;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebMvcTest(TaskController.class)
class TaskControllerWebTest {
@Autowired
private MockMvc mockMvc;
@MockitoBean
private TaskService taskService;
@Test
void getTasksReturnsOk() throws Exception {
when(taskService.findAll()).thenReturn(List.of());
mockMvc.perform(get("/tasks")).andExpect(status().isOk());
}
}Key points
- A test slice starts only one layer of the app.
- @WebMvcTest loads the named controller and its web parts.
- The service behind the controller is not started.
- @MockitoBean makes a fake service for the test.
- A fake stands in for the real service and returns set answers.
In this example, @WebMvcTest starts only TaskController and its web parts. The @MockitoBean field is a fake TaskService. The when line tells the fake to return an empty list. The test sends a GET request to /tasks. The andExpect call checks that the answer status is 200. The test run reports one test run with no failures.
Note
The fake service answers only what the test tells it to.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does @WebMvcTest start?