Spring Mockmvc忽略未知字段



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)));

检查未知字段并返回400 (BAD_RQUEST)是Jackson (ObjectMapper)的反序列化功能。它不是由Java的Bean验证处理的。

使用您的自定义MockMvc独立设置,您选择退出默认的Spring Boot自动配置,该配置将根据您配置的功能配置ObjectMapper

我建议使用@WebMvcTest(YourController.class)进行控制器测试,然后注入自动配置的MockMvc:

@WebMvcTest(YourController.class) // auto-configures everything in the background for your, including the ObjectMapper
class YourControllerTest {
@Autowired
private MockMvc mockMvc;

}