There is no @MockMvc annotation in Spring Boot. MockMvc is a class, and the annotation that makes Spring Boot create and inject one is @AutoConfigureMockMvc (or @WebMvcTest, which includes it). Together they let you test REST controllers by sending simulated GET, POST, PUT and DELETE requests and checking the responses, without starting a real server.
This article explains which annotation to pick, how to inject MockMvc, and how to test a REST API with it.
MockMvc (package org.springframework.test.web.servlet) is the object you call perform(...) on. Annotations only decide how it gets into your test:
| Annotation | What it loads | Use for |
|---|---|---|
@WebMvcTest(Controller.class) | Web layer only, plus an auto-configured MockMvc | Focused controller tests with mocked services |
@SpringBootTest + @AutoConfigureMockMvc | The full application context plus MockMvc | Integration tests across controller, service and database |
In Spring Boot 4, the test auto-configuration classes moved into per-technology modules, so import paths such as that of @AutoConfigureMockMvc differ from Boot 3. Let your IDE or the Spring Boot reference for your version supply the import.
Consider a small controller:
The test injects MockMvc and replaces the service with a Mockito mock:
@MockitoBean (Spring Framework 6.2 and later) is the replacement for @MockBean, which is deprecated.
Build requests with the static methods of MockMvcRequestBuilders and send JSON through content(...).
The delete test assumes the controller declares a 204 response for that endpoint. Each andExpect fails the test with a clear message if the status, header or JSON value does not match.
When you want real beans and a real database (for example Testcontainers), use @SpringBootTest with @AutoConfigureMockMvc:
This is slower than @WebMvcTest because it starts the whole context, but it exercises the real wiring. It still does not open a port; use webEnvironment = RANDOM_PORT when you need one.
@MockMvc on a field or class. It does not exist; use @Autowired MockMvc..contentType(MediaType.APPLICATION_JSON) on a POST, which returns 415.@WebMvcTest and expecting service or repository beans. They are not loaded; mock them.@WithMockUser or a CSRF token on state-changing requests.@WebMvcTest for web-layer slices and @AutoConfigureMockMvc for full-context tests. Both register a MockMvc bean you can autowire.
Yes. Build it with MockMvcBuilders.standaloneSetup(controller) or webAppContextSetup(context) in plain Spring.
No. Use WebTestClient for Spring WebFlux.
Add .andDo(print()) to the call chain to write both to the console while debugging.
@MockMvc is not a real annotation: MockMvc is the class and @AutoConfigureMockMvc or @WebMvcTest provides it. Use @WebMvcTest with @MockitoBean for quick controller tests, @AutoConfigureMockMvc with @SpringBootTest for integration tests, and assert on responses with status(), jsonPath() and header() matchers.