MockMvc Test Spring抛出org.springframework.web.HttpMediaTypeNotSupportedException

时间:2015-11-16 17:11:08

标签: spring unit-testing mockmvc

我正在尝试跟踪异常org.springframework.web.HttpMediaTypeNotSupportedException试图测试Json控制器。

控制器中的方法是:

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

My Spring Version是4.0.0.RELEASE

2 个答案:

答案 0 :(得分:0)

var germanPhone=new CultureInfo(0x00010407);
StringComparer germanPhoneICComp = StringComparer.Create(germanPhone, true);\\set to false if caps are important to you
var lstStrings7 = lstStrings.OrderBy(y => y, germanPhoneICComp).ToList();

答案 1 :(得分: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}"));