MockMvc
MockMvc는 실제 서블릿 컨테이너(톰캣 등)를 구동하지 않고도 Spring MVC Controller를 HTTP 요청 관점에서 테스트할 수 있게 해주는 클래스입니다.
즉, Spring의 DispatcherServlet, Controller, ArgumentResolver, Validator, ExceptionHandler 등 MVC 전체 흐름을 테스트 환경에서 그대로 재현할 수 있습니다.
내부 원리
MockMvc는 DispatcherServlet을 모의(Mock) 환경에서 동작시키고, HTTP 요청을 가상의 요청 객체 (MockHttpServletRequest)로 전달합니다.
이를 통해 실제 웹 브라우저에서 요청한 것처럼 Request Mapping, 파라미터 바인딩, 응답 객체 생성, 예외 처리 등이 모두 Spring MVC의 처리 흐름대로 수행됩니다.
사용 방법
1. 의존성 추가 (Spring Boot 기준)
testImplementation 'org.springframework.boot:spring-boot-starter-test'
- 해당 라이브러리에 MockMvc, Mockito, Hamcrest, AssertJ 등 기본적인 테스트 도구가 포함되어 있습니다.
2. 기본 테스트 설정
@WebMvcTest(controllers = UserController.class) // Controller 계층만 테스트
@AutoConfigureMockMvc
public class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void getUserById() throws Exception {
mockMvc.perform(get("/api/users/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("frend"))
.andDo(print());
}
}
- @WebMvcTest는 Web 레이어만 슬라이스(Slice) 테스트하며, Repository, Service 등은 Bean으로 등록되지 않습니다. 필요한 경우 @MockitoBean으로 주입해야 합니다.
3. 다양한 요청 메서드 지원
| HTTP 메서드 | MockMvc 메서드 |
| GET | get() |
| POST | post() |
| PUT | put() |
| PATCH | patch() |
| DELETE | delete() |
MockMvc 메서드 사용 예시
1. 요청 시뮬레이션 (perform())
mockMvc.perform(get("/api/products"))
2. 응답 검증 (andExpect())
.andExpect(status().isOk())
.andExpect(jsonPath("$.title").value("MacBook Pro"))
3. 요청/응답 출력 (andDo(print())
.andDo(print()); // 콘솔에 결과 출력
4. POST 요청 예시 (JSON 바디 포함)
mockMvc.perform(post("/api/products")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"title\": \"맥북\", \"price\": 2000000}"))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.title").value("맥북"));
5. 파라미터/헤더/쿠키 테스트도 가능
mockMvc.perform(get("/api/items/search")
.param("keyword", "keyboard")
.header("X-ACCESS-TOKEN", "token")
.cookie(new Cookie("user-id", "1234")))
.andExpect(status().isOk());
주의 사항
| 항목 | 설명 |
| 보안 필터 적용 여부 | Spring Security 사용 시 @AutoConfigureMockMvc(addFilters = false)로 필터 비활성화 가능 |
| 서비스 레이어 의존성 | @WebMvcTest는 Controller만 테스트하므로, 필요한 Bean(Service 등)은 @MockBean으로 직접 주입 |
| JSON 처리 | 요청/응답 객체는 ObjectMapper로 직렬화/역직렬화하는 것이 안정적입니다. |
MockMvc vs RestAssured vs WebTestClient
| 도구 | 사용 목적 | 특징 |
| MockMvc | 컨트롤러 단위 테스트 | 서버 없이 빠름, Spring MVC 전용 |
| RestAssured | 통합 테스트 | 실제 서버 띄워서 E2E 테스트 |
| WebTestClient | 비동기 WebFlux 환경 | Reactive API 테스트에 적합 |
언제 써야할까?
- 컨트롤러가 정상적으로 작동하는지 HTTP 관점에서 빠르게 검증하고 싶을 때
- Rest API 테스트 코드를 작성할 때
- 통합 테스트 전에 요청/응답 흐름이 잘 동작하는지 확인하고 싶을 때
요약
MockMvc는 Spring MVC 애플리케이션의 HTTP 요청과 응답 흐름을 실제 서버 없이 테스트할 수 있도록 도와주는 강력한 테스트 도구입니다.
출처
OpenAI의 ChatGPT (https://openai.com)
'프로그래머스 > Spring' 카테고리의 다른 글
| [Lombok] @Data (1) | 2025.04.13 |
|---|---|
| [Spring] 단위 테스트(Unit Test) vs 통합 테스트(Integration Test) (0) | 2025.03.28 |
| [Spring] JPA Specification (1) | 2025.02.19 |
| [Spring] Bean (1) | 2025.02.12 |
| [Spring] 페이징 (Paiging) 주요 메서드 (0) | 2025.02.10 |