已完成 406 NOT_ACCEPTABLE - 在 SpringBoot 中测试 WebLayer

Nuñ*_*ada 5 java rest spring json spring-boot

我在 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);


} 
Run Code Online (Sandbox Code Playgroud)

和这个测试:

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

这是测试的结果:

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 = []
Run Code Online (Sandbox Code Playgroud)

@JsonSerialize(as = IWildProject.class)
public interface IWildProject {
..
}
Run Code Online (Sandbox Code Playgroud)

use*_*814 0

你的问题有两个方面。

根本问题是您没有注册正确的消息转换器来编写 json 响应。这是隐藏的,因为错误配置服务器应该返回 500 而不是 406,因为控制器已指定生成注释并且客户端已接受所有标头。

更多详细信息 - https://github.com/spring-projects/spring-framework/issues/23287

这不再是最新版本中的问题,仅是 2.1.x spring boot 版本的问题。