
MockMvc에 대한 의문점을 가지게 되었다.@AutoConfigureMockMvc이 어노테이션을 무엇을 의미하는 것 일까??MockMvc는 Spring Framework에서 제공하는 Spring MVC 웹 애플리케이션의 요청과 응답을 테스트하기 위한 도구이다. 실제로 서버를 구동하지 않고도 컨트롤러와 상호작용하며 테스트를 수행할 수 있다.
서버를 구동하지 않음
HTTP 요청/응답의 모사
GET, POST, PUT, 등)을 모사하고 응답을 확인할 수 있다.유연한 응답 검증
Spring MVC 기능 테스트
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 응답 검증
}
}
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());
}
}
응답 본문에 포함된 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));
}
요청 생성 메서드
get(), post(), put(), delete(): HTTP 메서드 요청을 생성한다.응답 검증 메서드
andExpect(): 응답 상태 코드, 헤더, 본문 등을 검증한다.andDo(): 요청과 응답을 출력하거나 추가 작업을 수행한다.결과 처리
andReturn(): 수행 결과를 반환하여 추가 작업에 활용할 수 있다.@AutoConfigureMockMvc는 Spring Boot 테스트 환경에서 MockMvc를 자동으로 설정해 주는 어노테이션이다. 이를 통해 MockMvc 객체를 직접 생성하거나 설정할 필요 없이, 바로 주입받아 사용할 수 있다.
MockMvc 자동 설정
MockMvc 객체를 자동으로 생성하고, 테스트에 주입한다.테스트 환경 구성 간소화
MockMvc 객체를 수동으로 생성하거나 MockMvcBuilders를 사용할 필요 없이, 테스트 클래스에 @Autowired로 주입받아 바로 사용할 수 있다.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 상태 확인
}
}
@SpringBootTest: 애플리케이션 컨텍스트를 로드하는 통합 테스트 설정이다.@WebMvcTest: 특정 컨트롤러나 Spring MVC 컴포넌트만 테스트하고 싶을 때 사용한다.@WebMvcTest(MyController.class) // MyController만 테스트
@AutoConfigureMockMvc
public class MyControllerTest {
@Autowired
private MockMvc mockMvc;
}
| MockMvc (모의 환경) | 실제 서버 |
|---|---|
| 서버를 실행하지 않음 | 서버를 실행해야 한다. |
| 애플리케이션의 내부 로직을 테스트함 | 실제 네트워크 요청/응답을 테스트함 |
| 빠른 테스트 속도 | 테스트 속도가 느릴 수 있다. |
| 외부 네트워크 설정 불필요 | 네트워크 환경 설정이 필요하다. |
| 단위/통합 테스트에 적합 | E2E 테스트에 적합하다. |
MockMvc는 서버를 실행하지 않고도 컨트롤러와 요청-응답 체인을 빠르고 효율적으로 테스트할 수 있는 도구이다.@AutoConfigureMockMvc는 MockMvc를 자동으로 설정해 주는 어노테이션으로, 테스트 환경 구성을 간소화해 준다.