简体   繁体   中英

How to write a test to send json to a @RequestBody method by spring mvc test

My test

  ObjectMapper objectMapper = new ObjectMapper();
  objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
  byte[] bytes = objectMapper.writeValueAsBytes(webFile);
  this.mockMvc.perform(post("/loadFile.json").accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_JSON).content(bytes)).andExpect(status().isOk());

My Controller

@RequiredPermission(RequiredPermission.OperationType.viewProject)
@RequestMapping(value = "/loadFile", method = RequestMethod.POST)
public
@ResponseBody
ModelAndView load(@RequestBody WebFile document)
         { ... }

But always get 400 error

In your test you are using URL /loadFile.json but in your controller you have /loadFile . Are you using some urlrewriter if not change the url in test class to /loadFile . All other codes in test class seems to be Ok.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM