我正在测试api端点,并且MockMvc抛出org.springframework.web.HttpMediaTypeNotSupportedException预期状态:<201>但原为:<415> 阅读有关类似问题的所有文章-解决方案始终是内容类型的,但在这种情况下不是) 奇怪的是,我在MockHttpServletResponse的标头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>
答案 0 :(得分:0)
答案很简单。
在测试类中带有@MockBean
批注的服务正在创建实体并将其保存到db,然后控制器返回了实体ID,该实体ID在entity.getId()
中进行了NPE,当然在其余控制器的测试中进行了HTTP 415方法。同时,在真实数据库中进行测试时,邮递员未显示错误,因为服务层始终以.getId()
方法返回真实ID。
在我修改了服务层代码以检查实体是否为空之后,问题就消失了。