# Testing Controllers with MockMvc and Mockito

> How would you write a test for a POST endpoint using MockMvc and Mockito, including validation failure and error handling?

Canonical: https://www.internhack.in/learn/interview/spring-boot-interview/spring-mockito-mockmvc-testing
Last updated: 2026-11-28

Difficulty: Intermediate

## Question

How would you write a test for a POST endpoint using MockMvc and Mockito, including validation failure and error handling?

## Answer

Testing a REST controller thoroughly means checking more than the happy path. You want to know that the URL maps correctly, the JSON is parsed, validation rejects bad input with a 400, the service is called with the right arguments, and errors turn into the right status codes. MockMvc lets you do all of that without starting a real server, so tests run in a few hundred milliseconds.

MockMvc simulates the DispatcherServlet. In a @WebMvcTest it is auto-configured and injected. You build a request with the static helpers, such as post("/api/students"), set contentType and content, and perform it. Then you chain andExpect assertions on status, headers, and the response body, often using jsonPath expressions like $.email to inspect JSON fields. andDo(print()) dumps the whole exchange when debugging.

Mockito replaces the collaborators the controller depends on. In a web slice, the service is not loaded, so you declare it with @MockBean, and Boot registers a Mockito mock as that bean. You then stub behaviour with when(service.create(any())).thenReturn(dto), and afterwards verify interactions with verify(service).create(any()). Use argument matchers consistently: if one argument uses a matcher like any() or eq(), all of them must. ArgumentCaptor lets you capture the object passed to the service and assert on its fields, useful to prove the controller mapped the request correctly. For void methods use doThrow(...).when(mock).method(...). To simulate failure, thenThrow(new DuplicateEmailException(...)) and check that your @ControllerAdvice converts it to a 409.

Secure endpoints add a wrinkle. With Spring Security on the classpath, @WebMvcTest applies the security filter chain, so unauthenticated requests get 401 or 403, and POSTs without a CSRF token are rejected. Use spring-security-test with @WithMockUser(roles = "ADMIN") to simulate a logged-in user, add csrf() if CSRF is enabled, or import your test security configuration. Forgetting this is the number one reason developers see a mysterious 401 in a test that looks correct.

Some good testing habits. Name tests by behaviour, such as returns400WhenEmailInvalid. Follow arrange, act, assert. Convert the request object to JSON with an ObjectMapper instead of hand-writing strings, which avoids typos. Do not mock the class under test, and do not verify trivial interactions excessively, since that couples the test to implementation. Test one behaviour per method. And keep business logic tests in plain unit tests with Mockito and no MockMvc, so failures point precisely at the layer at fault.

Mockito internals may be probed: mocks are created with bytecode generation, by default via inline mock maker in recent versions, which can mock final classes. Spies wrap a real object to stub only some methods, but prefer mocks. With Mockito strictness under MockitoExtension, unused stubs cause failures, which helps keep tests clean.

## Code examples

### Controller test: success, validation and conflict

```
@WebMvcTest(StudentController.class)
class StudentControllerTest {

    @Autowired MockMvc mvc;
    @Autowired ObjectMapper mapper;
    @MockBean StudentService service;

    @Test
    void createsStudent() throws Exception {
        var req = new CreateStudentRequest("Asha", "asha@x.com", "9876543210", 3, null);
        when(service.create(any())).thenReturn(new StudentDto(1L, "Asha"));

        mvc.perform(post("/api/students")
                .contentType(MediaType.APPLICATION_JSON)
                .content(mapper.writeValueAsString(req)))
           .andExpect(status().isCreated())
           .andExpect(header().string("Location", "/api/students/1"))
           .andExpect(jsonPath("$.name").value("Asha"));

        ArgumentCaptor<CreateStudentRequest> captor = ArgumentCaptor.forClass(CreateStudentRequest.class);
        verify(service).create(captor.capture());
        assertEquals("asha@x.com", captor.getValue().email());
    }

    @Test
    void rejectsInvalidEmail() throws Exception {
        var bad = new CreateStudentRequest("Asha", "not-an-email", "9876543210", 3, null);
        mvc.perform(post("/api/students")
                .contentType(MediaType.APPLICATION_JSON)
                .content(mapper.writeValueAsString(bad)))
           .andExpect(status().isBadRequest())
           .andExpect(jsonPath("$.email").exists());
        verifyNoInteractions(service);
    }

    @Test
    void mapsDuplicateToConflict() throws Exception {
        when(service.create(any())).thenThrow(new DuplicateEmailException("asha@x.com"));
        mvc.perform(post("/api/students")
                .contentType(MediaType.APPLICATION_JSON)
                .content("{\"name\":\"Asha\",\"email\":\"asha@x.com\",\"phone\":\"9876543210\",\"year\":3}"))
           .andExpect(status().isConflict());
    }
}
```

The test covers the success path, validation short-circuiting before the service, and exception translation by the advice.

## Key points

- @MockBean registers a Mockito mock in the Spring context; @Mock is plain Mockito.
- Use @WithMockUser and csrf() when Spring Security is active.
- If one argument uses a matcher, all must use matchers.
- ArgumentCaptor verifies what the controller passed to the service.

## Common follow-up questions

- How do you test a secured endpoint with a JWT?
- Difference between mock and spy?
- Why verifyNoInteractions after a validation failure?

## Interview tips

- Show a failure-path test, not only success; this is what interviewers look for.
- Mention the security test wrinkle to demonstrate real experience.

## Concepts covered

MockMvc, Mockito, Stubbing, Verify

Previous: [Testing: @SpringBootTest vs @WebMvcTest vs @DataJpaTest](https://www.internhack.in/learn/interview/spring-boot-interview/spring-testing-slices) · Next: [Circular Dependencies in Spring and How to Fix Them](https://www.internhack.in/learn/interview/spring-boot-interview/spring-circular-dependencies) · [All of Spring Boot](https://www.internhack.in/learn/interview/spring-boot-interview)

## More Spring Boot questions

- [Spring vs Spring Boot: What Problem Does Boot Solve?](https://www.internhack.in/learn/interview/spring-boot-interview/spring-vs-spring-boot)
- [Inversion of Control and Dependency Injection Explained](https://www.internhack.in/learn/interview/spring-boot-interview/spring-ioc-dependency-injection)
- [Constructor vs Setter vs Field Injection](https://www.internhack.in/learn/interview/spring-boot-interview/spring-injection-types-constructor-preferred)
- [ApplicationContext vs BeanFactory](https://www.internhack.in/learn/interview/spring-boot-interview/spring-applicationcontext-vs-beanfactory)
- [Spring Bean Scopes and the Singleton Trap](https://www.internhack.in/learn/interview/spring-boot-interview/spring-bean-scopes)
- [Spring Bean Lifecycle Step by Step](https://www.internhack.in/learn/interview/spring-boot-interview/spring-bean-lifecycle)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [Spring Boot](https://www.internhack.in/learn/interview/spring-boot-interview)
