@SpringBootTest
애플리케이션의 전체 컨텍스트를 로드하여 테스트할 수 있다.
@WebMvcTest(UserController.class)
컨트롤러가 예상대로 작동하는지 테스트하기 위해 사용
Web Layer만 로드하며 특정 항목들만 스캔하도록 제한하여 보다 빠르고 가벼운 테스트 가능
@AutoConfigureMockMvc
MockMvc 인스턴스가 자동으로 구성
컨트롤러 뿐만 아니라 서비스, 레포지토리 계층의 객체들도 모두 로드한다.
스프링에서 제공하는 웹 어플리케이션 테스트용 라이브러리로, HTTP 요청을 작성하고 컨트롤러의 응답을 검증할 수 있다.
이를 통해 통합 테스트를 실행하지 않고 컨트롤러의 동작을 확인할 수 있다.

| 리턴 타입 | 메서드 | 설명 |
|---|---|---|
ResultActions | perform(RequestBuilder requestBuilder) | HTTP 요청을 실행하고 ResultActions 객체 반환 |
DispatcherServlet | getDispatcherServlet() | MockMvc가 초기화된 DispatcherServlet 객체 반환 |
ResultActionsMockMvc를 사용하여 실행한 HTTP 요청에 대한 결과를 나타낸다.
컨트롤러의 응답을 검증하고 원하는 동작을 수행 가능
| 리턴 타입 | 메서드 | 설명 |
|---|---|---|
ResultActions | andDo(ResultHandler handler) | 결과에 대한 추가 작업 실행 |
ResultActions | andExpect(ResultMatcher matcher) | 결과에 대한 기대치로 ResultMatcher 추가 |
ResultActions | andExpect(ResultMatcher matcher) | 결과에 대한 기대치로 ResultMatcher 추가 |
ResultActions | andExpectAll(ResultMatcher... matchers) | 여러 ResultMatcher에 대한 기대치를 반환 |
MvcResult | andReturn() | 수행된 요청 결과를 MvcResult 객체로 반환 |
MvcResultMockMvc에서 수행된 MVC 요청 결과에 대한 상세한 정보 제공
응답상태, 헤더, 바디 등과 같은 정보를 추출할 수 있다.
| 리턴 타입 | 메서드 | 설명 |
|---|---|---|
ModelAndView | getModelAndView() | 응답에 대한 모델과 뷰를 담고 있는 ModelAndView 객체를 반환 |
MockHttpServletRequest | getRequest() | 응답과 관련된 HttpServletRequest 객체를 반환 |
MockHttpServletResponse | getResponse() | 응답과 관련된 HttpServletResponse 객체를 반환 |
Object | getHandler() | 실행된 헨들러 객체를 반환 |
Exception | getResolvedException() | 핸들러에 의해 성공적으로 처리된 예외 반환 |
@Test
public void addArticle() throw Exception {
// given
AddArticleRequest request = new AddArticleRequest("title", "content");
String requestBody = objectMapper.writeValueAsString(request);
// when
ResultActions res = mockMvc.perform(post("/api/articles")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(requestBody));
// then
res.andExpect(status().isCreated());
.andExpect(jsonPath("$.title").value("title"))
.andExpect(jsonPath("$.content").value("content"));