실제 서블릿 컨테이너(Tomcat 등)를 띄우지 않고, 스프링 MVC의 동작을 재현하여 컨트롤러 레이어를 테스트할 수 있게 해주는 프레임워크.
장점: 서버를 구동하지 않으므로 테스트 속도가 매우 빠르고, HTTP 요청과 응답을 모킹(Mocking)하여 세밀하게 검증할 수 있다.
@WebMvcTest(테스트할컨트롤러.class)
@Autowired private MockMvc mockMvc
@MockBean
@WebMvcTest(OrderController.class)
class OrderControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private OrderService orderService; // 컨트롤러가 의존하는 서비스 모킹
@Test
@DisplayName("주문 단건 조회 테스트")
void getOrderTest() throws Exception {
// [Given] 가짜 데이터 및 동작 정의
Long orderId = 1L;
given(orderService.getOrder(orderId))
.willReturn(new OrderResponse(orderId, "PENDING"));
// [When & Then] 요청을 보내고 검증함
mockMvc.perform(get("/api/orders/{id}", orderId)) // GET 요청
.andExpect(status().isOk()) // 200 OK 확인
.andExpect(jsonPath("$.id").value(1L)) // JSON 응답값 검증
.andExpect(jsonPath("$.status").value("PENDING"))
.andDo(print()); // 전체 결과 출력
}
}
요청(Perform) 관련
| 메서드 | 설명 |
|---|---|
| get("/url") | GET 요청 생성 |
| post("/url").content(json).contentType(MediaType.APPLICATION_JSON) | POST 요청 및 본문 전송 |
| param("key", "value") | 쿼리 파라미터 전달 |
검증(Expect) 관련
| 메서드 | 설명 |
|---|---|
| status().isOk() | HTTP 200 응답 확인 |
| status().isCreated() | HTTP 201 응답 확인 |
| jsonPath("$.field").value("val") | JSON 응답의 특정 필드값 확인 |
| view().name("index") | 반환되는 뷰 이름 확인 (Thymeleaf 등 사용 시) |