Mocking dependencies in Spring MVC tests isolates a controller from its real services and databases so tests run fast and only verify the web layer's behavior. Spring provides dedicated test slicing and mocking support for exactly this purpose.
Key Points: • @WebMvcTest loads only the web layer — controllers, filters, and related MVC infrastructure — instead of the full application context, keeping tests fast. • @MockBean replaces a real Spring-managed bean (like a service) with a Mockito mock inside the test's application context. • Mockito's when()/thenReturn() stubs the mocked service's behavior so the controller can be tested against known inputs and outputs. • MockMvc, auto-configured by @WebMvcTest, simulates HTTP requests against the controller without starting a real servlet container. • This approach tests request mapping, validation, status codes, and serialization without needing a real database or network calls, making it suitable for fast CI runs.
Example: A test for GET /users/1 can use @MockBean UserService with when(userService.findById(1L)).thenReturn(testUser), then assert through MockMvc that the endpoint returns a 200 status with the expected JSON body, all without touching a real database.
Code Example:
@WebMvcTest(UserController.class)
class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private UserService userService;
@Test
void returnsUser() throws Exception {
when(userService.findById(1L)).thenReturn(new User(1L, "Amol"));
mockMvc.perform(get("/users/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("Amol"));
}
}Interview Tip: A concise interview answer is:
"I use @WebMvcTest to load just the web layer, @MockBean to replace real services with Mockito mocks, and MockMvc to simulate HTTP requests against the controller. That combination lets me verify routing, status codes, and JSON output without a real database or full application context."