[Spring] MockMvc와 @AutoConfigureMockMvc

호이·2025년 1월 17일

Spring

목록 보기
3/3

1. 의문점

  • 스프링 부트를 학습하는 도중 컨트롤러에 대한 테스트 코드를 작성 중에 MockMvc에 대한 의문점을 가지게 되었다.@AutoConfigureMockMvc이 어노테이션을 무엇을 의미하는 것 일까??

2. MockMvc란?

MockMvc는 Spring Framework에서 제공하는 Spring MVC 웹 애플리케이션의 요청과 응답을 테스트하기 위한 도구이다. 실제로 서버를 구동하지 않고도 컨트롤러와 상호작용하며 테스트를 수행할 수 있다.

1. 주요 특징

  1. 서버를 구동하지 않음

    • 실제 애플리케이션 서버를 실행하지 않고, 애플리케이션 컨텍스트에서 컨트롤러와 관련된 동작을 테스트할 수 있다.
    • 빠르고 독립적인 테스트가 가능하다.
  2. HTTP 요청/응답의 모사

    • HTTP 요청(GET, POST, PUT, 등)을 모사하고 응답을 확인할 수 있다.
  3. 유연한 응답 검증

    • 응답 코드, 헤더, 본문(JSON, XML 등)을 유연하게 검증할 수 있다.
  4. Spring MVC 기능 테스트

    • DispatcherServlet, 컨트롤러, 서비스, 필터 등 Spring MVC의 전체 요청 처리 체인을 테스트할 수 있다.

2. MockMvc 사용 예제

1. 기본 MockMvc 설정

Spring Boot 환경에서 @SpringBootTest@AutoConfigureMockMvc를 사용하여 자동으로 설정하는 방식이다.

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.web.servlet.MockMvc;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@SpringBootTest
@AutoConfigureMockMvc
public class MyControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    void testExampleEndpoint() throws Exception {
        mockMvc.perform(get("/api/example")) // GET 요청 수행
               .andExpect(status().isOk()); // HTTP 200 응답 검증
    }
}

2. 수동 설정

MockMvcBuilders를 사용하여 특정 컨트롤러를 수동으로 설정하는 방법이다.

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

public class StandaloneControllerTest {

    private MockMvc mockMvc;

    @BeforeEach
    void setup() {
        // 특정 컨트롤러만 테스트
        mockMvc = MockMvcBuilders.standaloneSetup(new MyController()).build();
    }

    @Test
    void testGetEndpoint() throws Exception {
        mockMvc.perform(get("/api/example"))
               .andExpect(status().isOk());
    }
}

3. 응답 내용 검증

응답 본문에 포함된 JSON 데이터를 검증하는 예제이다.

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@Test
void testJsonResponse() throws Exception {
    mockMvc.perform(get("/api/example"))
           .andExpect(status().isOk())
           .andExpect(content().contentType("application/json"))
           .andExpect(jsonPath("$.name").value("John Doe"))
           .andExpect(jsonPath("$.age").value(30));
}

3. 주요 메서드

  1. 요청 생성 메서드

    • get(), post(), put(), delete(): HTTP 메서드 요청을 생성한다.
  2. 응답 검증 메서드

    • andExpect(): 응답 상태 코드, 헤더, 본문 등을 검증한다.
    • andDo(): 요청과 응답을 출력하거나 추가 작업을 수행한다.
  3. 결과 처리

    • andReturn(): 수행 결과를 반환하여 추가 작업에 활용할 수 있다.

3. @AutoConfigureMockMvc란?

@AutoConfigureMockMvc는 Spring Boot 테스트 환경에서 MockMvc를 자동으로 설정해 주는 어노테이션이다. 이를 통해 MockMvc 객체를 직접 생성하거나 설정할 필요 없이, 바로 주입받아 사용할 수 있다.

1. 역할

  1. MockMvc 자동 설정

    • Spring Boot가 애플리케이션 컨텍스트에서 MockMvc 객체를 자동으로 생성하고, 테스트에 주입한다.
    • 컨트롤러, 필터, 인터셉터 등 Spring MVC의 주요 구성 요소를 쉽게 테스트할 수 있다.
  2. 테스트 환경 구성 간소화

    • MockMvc 객체를 수동으로 생성하거나 MockMvcBuilders를 사용할 필요 없이, 테스트 클래스에 @Autowired로 주입받아 바로 사용할 수 있다.

2. 예제: @AutoConfigureMockMvc 사용하기

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.web.servlet.MockMvc;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@SpringBootTest
@AutoConfigureMockMvc // MockMvc 자동 설정
public class MyControllerTest {

    @Autowired
    private MockMvc mockMvc; // 자동으로 주입됨

    @Test
    void testGetEndpoint() throws Exception {
        mockMvc.perform(get("/api/example")) // GET 요청 수행
               .andExpect(status().isOk()); // HTTP 200 상태 확인
    }
}

3. @AutoConfigureMockMvc를 사용할 때 함께 쓰이는 어노테이션

  • @SpringBootTest: 애플리케이션 컨텍스트를 로드하는 통합 테스트 설정이다.
  • @WebMvcTest: 특정 컨트롤러나 Spring MVC 컴포넌트만 테스트하고 싶을 때 사용한다.
@WebMvcTest(MyController.class) // MyController만 테스트
@AutoConfigureMockMvc
public class MyControllerTest {
    @Autowired
    private MockMvc mockMvc;
}

4. MockMvc와 실제 서버 비교

MockMvc (모의 환경)실제 서버
서버를 실행하지 않음서버를 실행해야 한다.
애플리케이션의 내부 로직을 테스트함실제 네트워크 요청/응답을 테스트함
빠른 테스트 속도테스트 속도가 느릴 수 있다.
외부 네트워크 설정 불필요네트워크 환경 설정이 필요하다.
단위/통합 테스트에 적합E2E 테스트에 적합하다.

5. 결론

  • MockMvc는 서버를 실행하지 않고도 컨트롤러와 요청-응답 체인을 빠르고 효율적으로 테스트할 수 있는 도구이다.
  • @AutoConfigureMockMvc는 MockMvc를 자동으로 설정해 주는 어노테이션으로, 테스트 환경 구성을 간소화해 준다.
  • 단위 테스트와 통합 테스트에서 매우 유용하며, 실제 서버를 띄우는 부담 없이 기능을 검증하는 데 적합하다.
profile
기억하기 싫어서 기록하는 작은 공간

0개의 댓글