spring - MockMvc 测试 Spring 抛出 org.springframework.web.HttpMediaTypeNotSupportedException

标签 spring unit-testing mockmvc

我在尝试测试 Json Controller 时遇到以下异常 org.springframework.web.HttpMediaTypeNotSupportedException。

Controller 中的方法是:

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

我的 Spring 版本是 4.0.0.RELEASE

最佳答案

您需要设置内容类型。

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

关于spring - MockMvc 测试 Spring 抛出 org.springframework.web.HttpMediaTypeNotSupportedException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33740880/

相关文章:

Spring Boot - MockMVC 测试不起作用

java - Spring JDBCTemplate 总是抛出 QueryTimeOutException

python - 如何覆盖时间戳字段以进行单元测试?

asp.net-mvc - 如何模拟asp.net mvc中的缓存对象?

c# - 最小起订量记录器和验证调用失败

spring - MockMvc 和 WebTestClient 有什么区别?

java - Spring Testing Mock MVC 不应用自定义 RequestMappingHandlerMapping

java - 如何用 Spring + Hibernate + MySQL 实现搜索过滤器?

java - 将 spring 请求主体转换为对象列表

java - 用于 Spring Boot 应用程序的 Logback 自定义数据库附加程序