【问题标题】:MockMvc throws HttpMediaTypeNotSupportedException Status expected: 201 but was 415MockMvc 抛出 HttpMediaTypeNotSupportedException 预期状态:201 但为 415
【发布时间】:2020-05-22 17:25:18
【问题描述】:

我正在测试一个 api 端点,MockMvc 抛出 org.springframework.web.HttpMediaTypeNotSupportedException 预期状态: 但原为: 阅读所有关于类似问题的 SO - 总是解决方案是内容类型,但在这种情况下不是) 奇怪的是,我在 MockHttpServletResponse 的 header application/json 中看不到。

控制器:

public static final String MEDIA_TYPE_APPLICATION_JSON_UTF8 = "application/json;charset=utf-8";
@PostMapping(value = "/api/Register", consumes = MEDIA_TYPE_APPLICATION_JSON_UTF8, produces = MEDIA_TYPE_APPLICATION_JSON_UTF8)
public ResponseEntity<Map<String, String>> register(@RequestBody Map<String, String> jsonMap) {
  ...
  Map<String, String> responseMap = new HashMap<>();
  MediaType MEDIA_TYPE_JSON_UTF8 = new MediaType("application", "json", StandardCharsets.UTF_8);
  HttpHeaders headers = new HttpHeaders();
  headers.setAccept(Arrays.asList(MEDIA_TYPE_JSON_UTF8));
  headers.setContentType(MEDIA_TYPE_JSON_UTF8);
  ...
  return new ResponseEntity<>(new Gson().toJson(responseMap), headers, HttpStatus.CREATED);
}

测试:

@Test
void Register_phoneNumber_returnOk() throws Exception {
  Map<String, String> body = new HashMap<>();
  body.put("phone", "1112223344");
  Gson gson = new Gson();
  String json = gson.toJson(body);
  MockHttpServletRequestBuilder request = post("/api/Register");
  request.content("{\"phone\":\"1112223344\"}");
  request.accept(MEDIA_TYPE_APPLICATION_JSON_UTF8);
  request.contentType(MEDIA_TYPE_APPLICATION_JSON_UTF8);
  mockMvc.perform(request)
                .andDo(print())
                .andExpect(status().isCreated());
}

错误:

WARN 6188 --- [main] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json;charset=utf-8' not supported]

    MockHttpServletRequest:
          HTTP Method = POST
          Request URI = /api/Register
           Parameters = {}
              Headers = [Content-Type:"application/json;charset=utf-8", Accept:"application/json;charset=utf-8"]
                 Body = {"phone":"1112223344"}
        Session Attrs = {}

    Handler:
                 Type = ru.controllers.MainController
               Method = ru.controllers.MainController#Register(Map)

    Async:
        Async started = false
         Async result = null

    Resolved Exception:
                 Type = org.springframework.web.HttpMediaTypeNotSupportedException

    ModelAndView:
            View name = null
                 View = null
                Model = null

    FlashMap:
           Attributes = null

    MockHttpServletResponse:
               Status = 415
        Error message = null
              Headers = [Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers", Accept:"application/octet-stream, text/plain, application/xml, text/xml, application/x-www-form-urlencoded, application/*+xml, multipart/form-data, multipart/mixed, */*"]
         Content type = null
                 Body = 
        Forwarded URL = null
       Redirected URL = null
              Cookies = []


    java.lang.AssertionError: Status expected:<201> but was:<415>

【问题讨论】:

    标签: java spring spring-boot mockito


    【解决方案1】:

    答案很简单。

    测试类中带有@MockBean 注释的服务正在创建实体并将它们保存到db,然后控制器返回实体ID,这在entity.getId() 中执行了NPE,当然,在rest 控制器的测试方法中,HTTP 415。同时在real db中测试,postman并没有报错,因为service层总是在.getId()方法中返回real id。 在我修改服务层代码以检查实体是否为空后,问题就消失了。

    【讨论】:

      猜你喜欢
      • 2014-06-27
      • 1970-01-01
      • 2019-02-26
      • 2020-11-28
      • 1970-01-01
      • 2022-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多