MockMvc for Controller Testing
Fast recall
Quick revision
Core answer
Whether you can write focused, fast controller tests that cover HTTP semantics without full integration overhead
Using @SpringBootTest + @AutoConfigureMockMvc for every controller test — it loads the full context unnecessarily; @WebMvcTest is faster and more focused
Mention testing validation errors (400 responses), exception handler output (@ControllerAdvice), and security with @WithMockUser
Interview-ready guide
Interview answer
MockMvc simulates HTTP requests through Spring's DispatcherServlet without starting a real server — no TCP, no socket binding. Combined with @WebMvcTest, it tests the controller layer in isolation: request mapping, parameter binding, @Valid annotation processing, @ControllerAdvice exception handling.
The test verifies the full HTTP contract — method, URL, content type, status code, response body, and headers. jsonPath() assertions check specific fields in the JSON response.
The key insight: validation tests don't need service mocks. Spring rejects invalid requests with @Valid before the controller method executes. The test verifies Spring's behavior, not your business logic.
MockMvc's limitation is that it bypasses the transport layer. CORS, SSL, and response compression only work with a real server via @SpringBootTest(webEnvironment = RANDOM_PORT) and TestRestTemplate.
MockMvc for Controller Testing
Direct Answer
MockMvc simulates the Spring MVC dispatch pipeline — including filters, interceptors, argument resolvers, and message converters — without starting an actual HTTP server. Use @WebMvcTest to load only the web layer and inject MockMvc, stub service dependencies with @MockBean, then perform requests with mockMvc.perform() and chain andExpect() assertions on status, headers, and JSON body.
Common Mistakes & Pitfalls
Using @SpringBootTest + @AutoConfigureMockMvc for every controller test — it loads the full context unnecessarily; @WebMvcTest is faster and more focused
Check your understanding
Answer these without looking back at the article.
- How do you test file upload endpoints with MockMvc?
- What is the difference between MockMvc and WebTestClient?
- How do you print the full request/response for debugging in MockMvc?
Related interview prep categories
1Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.