REST API - 201 응답 받기

2024. 8. 21. 14:11Spring기반 REST API개발

테스트 할 것

  • 입력값들을 전달하면 JSON 응답으로 201이 나오는지 확인.
    • Location 헤더에 생성된 이벤트를 조회할 수 있는 URI 담겨 있는지 확인
    • id는 DB에 들어갈 때 자동생성된 값으로 나오는지 확인
  • 입력값으로 누가 id나 eventStatus, offline, free 이런 데이터까지 같이 주면?
    • Bad_Request로 응답 vs 받기로 한 값 이외는 무시
  • 입력 데이터가 이상한 경우 Bad_Request로 응답
    • 입력값이 이상한 경우 에러
    • 비즈니스 로직으로 검사할 수 있는 에러
    • 에러 응답 메시지에 에러에 대한 정보가 있어야 한다.
  • 비즈니스 로직 적용 됐는지 응답 메시지 확인
    • offline 과 free 값 확인
  • 응답에 HATEOA와 profile 관련 링크가 있는지 확인.
    • self(view)
    • update(만든 사람은 수정할 수 있으니까)
    • events(목록으로 가는 링크)
  • API 문서 만들기
    • 요청 문서화
    • 응답 문서화
    • 링크 문서화
    • profile 링크 추가

 

EventController

package com.example.inflearnrestapi.events;

import org.springframework.hateoas.MediaTypes;
import org.springframework.hateoas.server.mvc.WebMvcLinkBuilder;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import java.net.URI;

import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn;


@Controller
@RequestMapping(value = "/api/events/",produces = MediaTypes.HAL_JSON_VALUE)
public class EventController {

    @PostMapping
    public ResponseEntity createEvent(@RequestBody Event event){

        URI createdUri = linkTo(methodOn(EventController.class)).slash("{id}").toUri();
        event.setId(10);
        return ResponseEntity.created(createdUri).body(event);
    }
}

 

EventControllerTest

package com.example.inflearnrestapi.events;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.hateoas.MediaTypes;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;

import java.time.LocalDateTime;

import static org.junit.jupiter.api.Assertions.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@WebMvcTest
class EventControllerTest {

    @Autowired
    MockMvc mockMvc;
    @Autowired
    ObjectMapper objectMapper;

    @Test
    public void createEvent() throws Exception {
        Event event = Event.builder()
                        .name("Spring")
                        .description("REST API Development with Spring")
                        .beginEnrollmentDateTime(LocalDateTime.of(2024,8,21,13,50))
                        .closeEnrollmentDateTime(LocalDateTime.of(2024,8,22,13,50))
                        .beginEventDateTime(LocalDateTime.of(2024,8,23,13,50))
                        .endEventDateTime(LocalDateTime.of(2024,8,24,13,50))
                        .basePrice(100)
                        .maxPrice(200)
                        .limitOfEnrollment(200)
                        .location("강남역 D2 스사텁 팩토리")
                        .build();


        mockMvc.perform(post("/api/events/")
                        .contentType(MediaType.APPLICATION_JSON)
                        .accept(MediaTypes.HAL_JSON)
                        .content(objectMapper.writeValueAsString(event)))  //perform 안에 주는게 요청
                .andDo(print())
                .andExpect(status().isCreated())
                .andExpect(jsonPath("id").exists());

    }




}