Performance: @WebMvcTest for controller testing
This affects test execution speed and resource usage during controller testing by limiting loaded components.
@WebMvcTest(UserController.class) public class UserControllerTest { @Autowired private MockMvc mockMvc; // tests }
@SpringBootTest
@AutoConfigureMockMvc
public class UserControllerTest {
@Autowired
private MockMvc mockMvc;
// tests
}| Pattern | Context Loaded | Startup Time | Memory Usage | Verdict |
|---|---|---|---|---|
| @SpringBootTest with @AutoConfigureMockMvc | Full app context | 1-3 seconds | High | [X] Bad |
| @WebMvcTest for controller only | Web layer only | 0.2-0.6 seconds | Low | [OK] Good |
@WebMvcTest in Spring Boot testing?@WebMvcTest for a controller named UserController?@WebMvcTest and MockMvc, what will be the HTTP status returned by the test?@WebMvcTest(controllers = HelloController.class)
public class HelloControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testHello() throws Exception {
mockMvc.perform(get("/hello"))
.andExpect(status().isOk());
}
}
@RestController
class HelloController {
@GetMapping("/hello")
public String sayHello() {
return "Hello World";
}
}@WebMvcTest test class that causes the test to fail with a NullPointerException.@WebMvcTest(controllers = UserController.class)
public class UserControllerTest {
private MockMvc mockMvc;
@Test
public void testGetUser() throws Exception {
mockMvc.perform(get("/user/1"))
.andExpect(status().isOk());
}
}OrderController that depends on a service OrderService. Using @WebMvcTest, how can you provide a mock OrderService to the controller during testing?Pass the test and this pattern moves unknown