首页 > 解决方案 > 完成 406 NOT_ACCEPTABLE - 在 SpringBoot 中测试 WebLayer

问题描述

我在 Spring Boot v2.1.0.RELEASE 应用程序中有这个方法。

@GetMapping(value = "/wildProject", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<WildProject>> getList(HttpServletRequest request,
        HttpServletResponse response)
        throws Exception {

    List<WildProject> list = authorisationService.getList();

    System.out.println("-----------------");
    System.out.println(list);
    System.out.println("-----------------");

    return ok().body(list);


} 

这个测试:

 this.mockMvc.perform(get("/wildProject")
  //.accept(MediaType.APPLICATION_JSON_UTF8_VALUE))
  // .andDo(print())
  .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
  .andExpect(status().isOk());

这是测试的结果:

20:03:38.253 [main] DEBUG o.s.w.s.m.m.a.HttpEntityMethodProcessor - Using 'application/json', given [*/*] and supported [application/json]
20:03:38.255 [main] WARN  o.s.w.s.m.s.DefaultHandlerExceptionResolver - Resolved [org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation]
20:03:38.256 [main] DEBUG o.s.t.w.s.TestDispatcherServlet - Completed 406 NOT_ACCEPTABLE

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /wildProject
       Parameters = {}
          Headers = {Content-Type=[application/json;charset=UTF-8]}
             Body = null
    Session Attrs = {}

Handler:
             Type = com.bonansa.controller.AuthorisationController
           Method = public org.springframework.http.ResponseEntity<java.util.List<com.bonansa.WildProject>> com.bonansa.controller.AuthorisationController.getList() throws java.lang.Exception

Async:
    Async started = false
     Async result = null

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

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

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 406
    Error message = null
          Headers = {}
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

@JsonSerialize(as = IWildProject.class)
public interface IWildProject {
..
}

标签: javajsonspringspring-bootrest

解决方案


您不需要Content-TypeGET请求设置标头,因为您没有发送任何内容而是请求某些内容。在这种Accept情况下,标题是要寻找的。

而且,MediaType.APPLICATION_JSON_VALUE不会匹配MediaType.APPLICATION_JSON_UTF8_VALUE

我建议将那段代码重构为:

this.mockMvc.perform(get("/wildProject")
  .accept(MediaType.APPLICATION_JSON_VALUE))
  // .andDo(print())
  .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
  .andExpect(status().isOk());

推荐阅读