【发布时间】: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