API方法已经使用@Valid注解进行了验证。当我使用postman测试此方法,并发布一个未知字段时,它可以工作,并拒绝请求。但是,当我使用mockMvc进行测试时,mockMvc会忽略未知字段。我想知道如何强制mockMvc来考虑API方法中的验证。
控制器
@PostMapping(value = "/path", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> notification(@Valid @RequestBody RequestClass requestPayload) {
}测试方法
MockHttpServletRequestBuilder builder = MockMvcRequestBuilders
.post("/path" )
.content("{\"fakeField\":\"fake\",\"userId\":\"clientId\"")
.contentType(MediaType.APPLICATION_JSON_VALUE);
String responseMessage = "Error message";
this.mockMvc =
standaloneSetup(myController)
.build();
this.mockMvc
.perform(builder)
.andDo(print())
.andExpect(status().is(HttpStatus.BAD_REQUEST.value()))
.andExpect(content().string(containsString(responseMessage)));发布于 2021-10-26 07:41:11
检查未知字段并返回400 (BAD_RQUEST)是Jackson ( ObjectMapper)的一个反序列化功能。它不是由Java的Bean验证处理的。
对于自定义的MockMvc独立设置,您可以选择不使用默认的Spring Boot自动配置,它将根据您配置的功能配置ObjectMapper。
我建议使用@WebMvcTest(YourController.class) for your controller tests,然后注入自动配置的MockMvc
@WebMvcTest(YourController.class) // auto-configures everything in the background for your, including the ObjectMapper
class YourControllerTest {
@Autowired
private MockMvc mockMvc;
}https://stackoverflow.com/questions/69711852
复制相似问题