Spring Boot controller unit tests use the @WebMvcTest slice annotation to load only the web layer, combined with MockMvc to simulate HTTP requests and Mockito to stub out service dependencies.
A test for a GET /users/{id} endpoint mocks UserService.findById() to return a stub User, then asserts the MockMvc response has status 200 and a JSON body matching the expected name field.
@WebMvcTest(UserController.class)
class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private UserService userService;
@Test
void returnsUser() throws Exception {
when(userService.findById(1L)).thenReturn(new User(1L, "Amol"));
mockMvc.perform(get("/users/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("Amol"));
}
}A concise interview answer is
I use @WebMvcTest to load just the web layer, autowire MockMvc to simulate HTTP calls, and mock the service layer with @MockBean so the test only exercises controller behavior like routing, status codes, and serialization, without hitting real business logic or a database.
Last updated: 16 July 2026
Previous question: How do you handle session management in Spring Boot?
Next question: Can you list some of the endpoints provided by Spring Boot Actuator?