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.
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.
@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"));
}
}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.
Last updated: 16 July 2026
Previous question: What frameworks are used for testing Spring MVC components?
Next question: What are the best practices for integration testing in Spring MVC?