클라이언트가 보낸 요청 메시지 바디에 담긴 값의 타입을 받지 못할 때 발생한다. 예를 들어, 자바에서 JSON 으로 받아온 값을 객체로 만들 수 있도록 코드를 작성했을 때 클라이언트가 JSON 이 아닌 그 이외의 값을 보내면 415 상태코드가 반환된다.

예시

우아한테크코스 지하철 노선도 미션 중 지하철역을 생성하는 Controller 메서드이다.

@RestController
@RequestMapping("/stations")
public class StationController {

    private final StationService stationService;

    public StationController(StationService stationService) {
        this.stationService = stationService;
    }

    @PostMapping
    public ResponseEntity<StationResponse> createStation(@RequestBody @Valid StationRequest stationRequest) {
        long stationId = stationService.save(stationRequest);
        StationResponse stationResponse = new StationResponse(stationId, stationRequest.getName());
        return ResponseEntity.created(URI.create("/stations/" + stationId)).body(stationResponse);
    }

		// 생략
}

@RequestBody 어노테이션은 클라이언트가 JSON 으로 보낸 값을 받아와 자바 객체로 반환해주는 역할을 한다. 즉, 입력값이 JSON 이어야 한다.

createStation 메서드에 대한 테스트코드를 작성하였다. 올바른 URI 와 데이터를 입력하여도 에러가 발생한다.

@DisplayName("지하철역 관련 Controller 테스트")
@WebMvcTest(StationController.class)
class StationControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private StationService stationService;

    @DisplayName("지하철역을 생성한다.")
    @Test
    void createStation() throws Exception {
				// given
        String body = "{\\"name\\": \\"강남역\\"}";

        RequestBuilder request = MockMvcRequestBuilders
                .post("/stations")
                .content(body);

        // when & then
        mockMvc.perform(request)
                .andExpect(status().isCreated());
    }
}
MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /stations
       Parameters = {}
          Headers = [Content-Length:"21"]
             Body = {"name": "강남역"}
    Session Attrs = {}

MockHttpServletResponse:
           Status = 415
    Error message = null
          Headers = [Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers", Accept:"application/json, application/*+json"]
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

응답 메시지의 상태코드를 보면 415 이다. 문자열로 받은 값을 JSON 으로 자동으로 변환해주지 않아 발생하였다. 다음과 같이 요청 보내는 데이터의 형식이 JSON 임을 명시 하면 테스트코드가 통과된다.

@DisplayName("지하철역을 생성한다.")
@Test
void createStation() throws Exception {
    // given
    String body = "{\\"name\\": \\"강남역\\"}";

    RequestBuilder request = MockMvcRequestBuilders
            .post("/stations")
            .content(body)
            .contentType(MediaType.APPLICATION_JSON);

    // when & then
    mockMvc.perform(request)
            .andExpect(status().isCreated());
}