Skip to main content

Test Spring MVC Controllers with MockMvc

· One min read
Apache Wangye
Software developer and technical writer

MockMvc exercises Spring MVC request handling without starting a real HTTP server.

@WebMvcTest(UserController.class)
class UserControllerTest {
@Autowired MockMvc mockMvc;

@MockBean UserService userService;

@Test
void returnsUser() throws Exception {
given(userService.findById(1L))
.willReturn(new UserDto(1L, "Tom"));

mockMvc.perform(get("/users/{id}", 1))
.andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith("application/json"))
.andExpect(jsonPath("$.id").value(1))
.andExpect(jsonPath("$.name").value("Tom"));
}
}

Use @WebMvcTest for a focused controller slice and mock service dependencies. Use @SpringBootTest with @AutoConfigureMockMvc when filters, serialization, validation, security, and broader configuration must be integrated.

Assert both success and failure contracts: invalid input, missing resources, authorization, content type, and exception-handler responses. Avoid assertions that depend on irrelevant JSON field order.

Page views: --

Total views -- · Visitors --