How do you write unit tests for Spring Boot controllers?

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.

Key Points: • @WebMvcTest(SomeController.class) loads just the controller and MVC infrastructure, not the full application context, keeping tests fast. • MockMvc, autowired into the test, simulates HTTP calls without starting a real servlet container. • @MockBean replaces the controller's service dependencies with Mockito mocks configured with expected behavior. • Assertions on the response use MockMvc's fluent API to check status codes, headers, and JSON body content. • This slice test isolates controller logic like request mapping and validation from business logic in the service layer.

Example: 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.

Code Example:

@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"));
    }
}

Interview Tip: 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."