완료 406 NOT_ACCEPTABLE-SpringBoot에서 WebLayer 테스트

Dec 07 2020

이 메서드는 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 {
..
}

답변

s7vr Dec 19 2020 at 04:59

문제는 두 가지로 나타납니다.

json 응답을 작성할 수있는 올바른 메시지 변환기를 등록하지 않은 근본적인 문제입니다. 이것은 컨트롤러가 생성 주석을 지정하고 클라이언트가 모두의 헤더를 수락하기 때문에 잘못된 구성에 대해 서버가 406 대신 500을 반환해야하는 버그로 인해 숨겨져 있습니다.

자세한 내용은 - https://github.com/spring-projects/spring-framework/issues/23287

이것은 더 이상 2.1.x 스프링 부트 버전의 최신 릴리스에서만 문제가되지 않습니다.

2 x80486 Dec 08 2020 at 00:48

아무것도 보내지 않고 요청하기 때문에 요청에 대한 Content-Type헤더 를 설정할 필요 GET가 없습니다. 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());