REST API TDD

Metronon·2024년 12월 24일

REST-API

목록 보기
6/12
post-thumbnail

@ActiveProfiles

@ActiveProfiles 어노테이션은 테스트시 지정된 프로파일로 테스트를 진행할 수 있도록 설정한다.

주요 특징

  1. 테스트 실행 시 지정된 프로파일을 활성화한다.
  2. 여러 프로파일을 동시에 활성화할 수 있다.
  3. 테스트 환경에 맞는 설정을 로드하는데 유용하다.
@ActiveProfiles("test") // 단일 프로파일
@ActiveProfiles({"test", "local"}) // 복수 프로파일

활용 사례

  • 테스트용 DB 설정 적용
  • 테스트 환경에 맞는 외부 서비스 설정
  • 테스트용 시큐리티 설정 적용
  • 캐시나 배치 작업 비활성화

장점

  • 실제 운영 환경과 분리된 테스트 환경 구성이 가능하다.
  • 테스트에 필요한 최소한의 설정만 로드할 수 있다.
  • 환경별 설정 관리 용이하다.

MockMvc

MockMvc는 스프링 MVC 테스트를 위한 핵심적인 클래스이다.

주요 특징

  1. 실제 서버를 구동하지 않고도 스프링 MVC의 동작을 재현할 수 있다.
  2. HTTP 요청을 시뮬레이션하여 컨트롤러를 테스트할 수 있다.
  3. 스프링 시큐리티와 통합되어 인증/인가 테스트도 가능하다.

코드 작성 방법

  1. @AutoConfigureMockMvc 어노테이션으로 MockMvc를 자동 구성
  2. @Autowired로 MockMvc 주입
  3. perform() 메서드로 요청 실행
  4. andExpect()로 응답 검증
  5. andDo()로 추가 작업 수행

주요 메서드

  • perform(): HTTP 요청 실행
  • andExpect(): 응답 결과 검증
  • andDo(): 요청/응답 내용 출력 등 추가 작업
  • contentType(): 요청 컨텐츠 타입 설정
  • content(): 요청 본문 설정
  • header(): 요청 헤더 설정

실제 Testcase 활용사례

@SpringBootTest
@ActiveProfiles("test")
@AutoConfigureMockMvc
@Transactional
public class MemberControllerTest{
	@Autowired
    private MemberService memberService;
    
    @Autowired
    private MockMvc mvc;
    
    @Test
    void joinTest() throws Exception {
    	ResultActions resultActions = mvc
        		.perform(
                	post("/members/join")
                	.content("""
                        	{
                                "username": "test",
                                "password": "1234",
                                "nickname": "test"
                             }
                             """.stripIndent())
    	.contentType(
    new MediaType(MediaType.APPLICATION_JSON, StandardCharsets.UTF_8)
    )
    )
    .andDo(print());

resultActions
                .andExpect(handler().handlerType(MemberController.class))
                .andExpect(handler().methodName("join"))
                .andExpect(status().isCreated())
                .andExpect(jsonPath("$.resultCode").value("201-1"))
                .andExpect(jsonPath("$.message").value("test님 환영합니다."))
profile
비전공 개발 지망생의 벨로그입니다!

0개의 댓글