2015-11-16 104 views
4

我收到以下例外org.springframework.web.HttpMediaTypeNotSupportedException嘗試測試Json控制器。MockMvc測試春天拋出org.springframework.web.HttpMediaTypeNotSupportedException

在控制器的方法是:

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

我的測試方法如下:

@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}")); 
    } 

但是,我得到這樣的迴應:

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 = [] 

我的春天版本是4.0 .0.RELEASE

+2

在這裏找到答案: http://stackoverflow.com/questions/31609496/httpmediatypenotsupportedexception-when-trying-to-test-handling-of-http-post –

+0

的可能的複製[HttpMediaTypeNotSupportedException試圖測試時的處理的HTTP POST](http://stackoverflow.com/questions/31609496/httpmediatypenotsupportedexception-when-trying-to-test-handling-of-http-post) – sebadagostino

回答

0

mockMvc.perform(put(「/ json/report」)。header(「hash」,「123456789」) .accept(MediaType.APPLICATION_JSON).content(asJsonString(report)))。contentType(MediaType.APPLICATION_JSON)。和()()()()()()(){(){「code \」:2,\「message \」:\「Session error \」,\「data \」:null}「)) ;

+0

你可以給你的代碼一些細節,特別是因爲它是如此不可讀?另外,將你的代碼加入到後面的''像這樣''來顯示它們'像這樣',這樣它就可以讀取。或者,您可以在行之前使用四個空格來渲染代碼,這對多行代碼很有幫助。 –

0

您需要設置內容類型。

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}")); 
相關問題