【发布时间】:2021-12-11 03:54:13
【问题描述】:
API 方法已经通过@Valid 注解进行了验证。当我使用邮递员测试此方法并发布未知字段时,它可以工作并拒绝请求。但是,当我使用 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)));
【问题讨论】:
-
问题是为什么您在生产代码中将
FAIL_ON_UNKNOWN_PROPERTIES设置为true,并在测试中设置为false。这归结为一个问题:您是如何配置 ObjectMapper 的?