MockMvc Spring throws test org.springframework.web.HttpMediaTypeNotSupportedException

I get the following org.springframework.web.HttpMediaTypeNotSupportedException exception trying to check the Json Controller.

Method in the controller:

@RequestMapping(value = "/report", method = RequestMethod.PUT) public @ResponseBody DatosJsonVO report(@RequestHeader(value = "hash", required = true) String hash, @RequestBody ReportVO report) { } 

My verification method is as follows:

 @Test public void reportarPreguntaSesionInvalida() throws Exception { ReportVO report = new ReportVO(); report.setIdQuestion(1); report.setIssue("Wrong answer"); mockMvc.perform(put("/json/report").header("hash", "123456789") .accept(MediaType.APPLICATION_JSON).content(asJsonString(report))).andDo(print()) .andExpect(content().string("{\"code\":2,\"message\":\"Session error\",\"data\":null}")); } 

But I get this answer:

 MockHttpServletRequest: HTTP Method = PUT Request URI = /json/report Parameters = {} Headers = {hash=[8.16615469E8], Accept=[application/json]} Handler: Type = com.controller.json.QuestionsJsonController Async: Was async started = false Async result = null Resolved Exception: Type = org.springframework.web.HttpMediaTypeNotSupportedException ModelAndView: View name = null View = null Model = null FlashMap: MockHttpServletResponse: Status = 415 Error message = null Headers = {} Content type = null Body = Forwarded URL = null Redirected URL = null Cookies = [] 

My Spring version 4.0.0.RELEASE

+5
source share
2 answers

mockMvc.perform (put ("/ json / report"). header ("hash", "123456789") Accept (MediaType.APPLICATION_JSON) .content (asJsonString (report))). CONTENTTYPE (MediaType.APPLICATION_JSON) .andDo (print ()) .andExpect (content (). String ("{\" code \ ": 2, \" message \ ": \" Session error \ ", \" data \ " : null} "));

0
source

You need to set the content type.

  mockMvc.perform(put("/json/report") .header("hash", "123456789") .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON_VALUE) .content(asJsonString(report))).andDo(print()) .andExpect(content().string("{\"code\":2,\"message\":\"Session error\",\"data\":null}")); 
0
source

Source: https://habr.com/ru/post/1236068/


All Articles