The API method has already been validated with @Valid annotation. When I test this method using postman, and post an unknown field, it works, and rejects the request. However, when I test this using mockMvc, mockMvc ignores unknown fields. Any idea how I can enforce mockMvc to consider the validation in the API method.
Controller
@PostMapping(value = "/path", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> notification(@Valid @RequestBody RequestClass requestPayload) {
}
Test method
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)));
Checking for unknown fields and returning a 400 ( BAD_RQUEST
) is a deserialization feature of Jackson (the ObjectMapper
). It's not handled by Java's Bean Validation.
With your custom MockMvc
standalone setup you opt-out of the default Spring Boot auto-configuration which would configure the ObjectMapper
according to your configured features.
I'd recommend using @WebMvcTest(YourController.class)
for your controller tests and then inject the auto-configured MockMvc
:
@WebMvcTest(YourController.class) // auto-configures everything in the background for your, including the ObjectMapper
class YourControllerTest {
@Autowired
private MockMvc mockMvc;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.