Testing a Spring MVC application means verifying that HTTP requests are routed correctly, controllers produce the right responses, and the web layer integrates properly with the rest of the app, typically without starting a real server.
Key Points: • JUnit is the standard test runner, and Mockito is used to mock dependencies like services or repositories. • MockMvc simulates HTTP requests against the DispatcherServlet without needing a running servlet container, making tests fast. • @WebMvcTest loads only the web layer (controllers, filters, converters) for focused, lightweight slice tests. • @SpringBootTest with a random port plus a real HTTP client (like TestRestTemplate or WebTestClient) is used for full end-to-end integration tests. • Assertions typically check status codes, response body content, and headers, using MockMvc's fluent expectation API.
Example: A test for a GET /users/1 endpoint might use MockMvc to perform the request, mock the UserService to return a fixed user, and assert the response status is 200 with a JSON body containing the expected username.
Code Example:
@WebMvcTest(UserController.class)
class UserControllerTest {
@Autowired MockMvc mockMvc;
@MockBean 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("$.username").value("Amol"));
}
}Interview Tip: A concise interview answer is:
"I use MockMvc with @WebMvcTest to test the web layer in isolation, mocking out service dependencies with @MockBean, and asserting on status codes and response bodies. For full end-to-end coverage I fall back to @SpringBootTest with a real HTTP client against a running context."