I'm testing an api endpoint and MockMvc throws org.springframework.web.HttpMediaTypeNotSupportedException Status expected:<201> but was:<415> Read all SO about similar problems - always solution is in content-type, but not in this case ) What is strange, I cannot see in MockHttpServletResponse's headers application/json.
Controller:
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:
@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());
}
Error:
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>
Answer was quite simple.
Service with @MockBean
annotation in test class was creating entities and saving them to db, then controller was returning entity id, that did NPE in entity.getId()
and, of course, HTTP 415 in rest controller's test method. At the same time while testing in real db, postman did not show an error, because service layer always returned real id in .getId()
method. After i modified service layer code to check entity for null, problem was gone.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.