REST API - 테스트 만들기

2024. 8. 21. 13:27Spring기반 REST API개발

스프링 부트 슬라이스 테스트

  • @WebMvcTest
  • MockMvc 빈을 자동 설정 해준다.
  • 웹 관련 빈만 등록해준다. (슬라이스)

 

MockMvc

  • 스프링 MVC 테스트 핵심 클래스
  • 웹 서버를 띄우지 않고도 스프링 MVC (DispatcherServlet)가 요청을 처리하는 과정을 확인할 수 있기 때문에 컨트롤러 테스트용으로 자주 쓰임.
package com.example.inflearnrestapi.events;

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 static org.junit.jupiter.api.Assertions.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@WebMvcTest
class EventControllerTest {

    @Autowired
    MockMvc mockMvc;

    @Test
    public void createEvent() throws Exception {
        mockMvc.perform(post("/api/events/")
                        .contentType(MediaType.APPLICATION_JSON_UTF8)
                        .accept(MediaTypes.HAL_JSON)
                )  //perform 안에 주는게 요청
                .andExpect(status().isCreated());
    }




}

 

테스트 할 것

  • 입력값들을 전달하면 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 링크 추가

 

 

'Spring기반 REST API개발' 카테고리의 다른 글

Event 생성 API 구현 : 입력값 제한하기  (0) 2024.08.22
REST API - 201 응답 받기  (0) 2024.08.21
Event 생성 API 구현 - 비즈니스 로직  (0) 2024.08.20
Event 도메인 구현  (0) 2024.08.20
Event REST API  (0) 2024.08.20