MockMvc
mockmvc (web layer tests) mockmvc tests spring mvc controllers without starting a real http server. it dispatches requests through the full filter
Introduction
MockMvc tests Spring MVC controllers without starting a real HTTP server. It dispatches requests through the full filter chain and returns MockHttpServletResponse — fast, isolated web layer tests.
Informative example
Controller test with MockMvc:
@WebMvcTest(UserController.class)class UserControllerTest {@Autowired MockMvc mvc;@MockBean UserService service;@Testvoid getUser() throws Exception {when(service.find(1L)).thenReturn(new UserDto(1L, "Ada"));mvc.perform(get("/api/users/1").accept(APPLICATION_JSON)).andExpect(status().isOk()).andExpect(jsonPath("$.name").value("Ada"));}@Testvoid createUserValidation() throws Exception {mvc.perform(post("/api/users").contentType(APPLICATION_JSON).content("{\"name\":\"\",\"email\":\"bad\"}")).andExpect(status().isBadRequest()).andExpect(jsonPath("$.errors.email").exists());}}
Best practices
- @WebMvcTest loads only the web layer — faster than @SpringBootTest.
- Use jsonPath for JSON assertions; content().json() for full body match.
- Test status codes, headers and body in separate focused tests.
Purpose of this lesson
Master MockMvc so you can apply it confidently in production Java code, technical interviews, and code reviews.
Step-by-step explanation
- Understand the core idea behind MockMvc.
- Walk through the runnable example and tweak it in the playground.
- Apply the pattern in a small Spring Boot or CLI exercise of your own.
- Re-read the common mistakes and interview Q&A to lock the concept in.
Interactive workflow diagram
Identify use case
Recognize when mockmvc is the right tool for the problem.
Useful template
MockMvc GET test
mvc.perform(get("/api/users/1").accept(APPLICATION_JSON)).andExpect(status().isOk()).andExpect(jsonPath("$.name").value("Ada"));
Debugging tips
- Read the full stack trace — Java's exception messages name the offending class and line.
- Reproduce in the smallest possible
main()method before fixing in the real app. - Use IntelliJ's debugger breakpoints and 'Evaluate Expression' rather than scattering
System.out.
Optimization strategies
- Profile before optimizing — JFR (Java Flight Recorder) and async-profiler reveal real hotspots.
- Prefer immutable data and stream pipelines over hand-rolled loops when readability matters.
- Reach for the right JDK collection (ArrayList vs LinkedList vs ArrayDeque) before writing custom data structures.
Enterprise example
Teams at Netflix, Uber and Goldman Sachs apply MockMvc daily — usually wrapped behind Spring Boot services with observability hooks (Micrometer + OpenTelemetry).
Interview questions & answers
Q1Explain MockMvc in one minute.
Q2When would you avoid MockMvc?
Summary
In this lesson you learned MockMvc — the concept, syntax, a runnable example, and the production pitfalls to avoid. Apply it in the playground before moving on.