Java Tutorial 0/145 lessons ~6 min read Lesson 77

    MockMvc

    mockmvc (web layer tests) mockmvc tests spring mvc controllers without starting a real http server. it dispatches requests through the full filter

    Course progress0%
    Focus
    12 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    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:

    ts
    @WebMvcTest(UserController.class)
    class UserControllerTest {
    @Autowired MockMvc mvc;
    @MockBean UserService service;
    @Test
    void 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"));
    }
    @Test
    void 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

    1. Understand the core idea behind MockMvc.
    2. Walk through the runnable example and tweak it in the playground.
    3. Apply the pattern in a small Spring Boot or CLI exercise of your own.
    4. Re-read the common mistakes and interview Q&A to lock the concept in.

    Interactive workflow diagram

    1MockMvc — typical flow
    1 / 4

    Identify use case

    Recognize when mockmvc is the right tool for the problem.

    Useful template

    MockMvc GET test

    java
    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.
    Describe what problem it solves, the JDK APIs involved, and one production trade-off.
    Q2When would you avoid MockMvc?
    Mention performance, complexity, or readability cases where a simpler approach wins.

    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.

    Ready to mark this lesson complete?Track your journey across the entire course.