Controller
@RestController
@Validated
class MyController {
@GetMapping("/foo")
public String unwrapped(@Min(1) @RequestParam("param") int param) {
return Integer.toString(param);
}
@GetMapping("/bar")
public String wrapped(@ModelAttribute @Valid Wrapper bean) {
return Integer.toString(bean.param);
}
static class Wrapper {
@Min(1)
int param;
public void setParam(final int param) {
this.param = param;
}
}
}
Test
public class MyControllerTest {
MyController controller = new MyController();
MockMvc mockMvc = MockMvcBuilders
.standaloneSetup(this.controller)
.build();
@Test // fails
public void unwrapped() throws Exception {
this.mockMvc.perform(get("/foo")
.param("param", "0"))
.andExpect(status().isBadRequest());
}
@Test // passes
public void wrapped() throws Exception {
this.mockMvc.perform(get("/bar")
.param("param", "0"))
.andExpect(status().isBadRequest());
}
}
To enable (unwrapped) method parameter validation in spring the controller has to be annotated with @Validated
and the MethodValidationPostProcessor
must be added to the context.
Is it possible to add the MethodValidationPostProcessor
bean to the standalone setup ?
The question might be reduced to how to add a BeanPostProcessor
to a standalone MockMvc setup ?