mockMvc의 andExpect()를 확장하여 더 자세히 테스트 하는 방법

public interface ResultActions {
ResultActions andExpect(ResultMatcher var1) throws Exception;

ResultActions andDo(ResultHandler var1) throws Exception;

MvcResult andReturn();
}

andExpect()를 변수로 추출하여

ResultActions result = mockMvc.perform(post("/events")
.param("name", "keesun")
.param("limit", "-10"))
.andExpect(status().isOk())
.andExpect(model().hasErrors());
ModelAndView mav = result.andReturn().getModelAndView();
Map<String, Object> model = mav.getModel();
System.out.print(model.size());

ModelAndView에서 모델을 가져와서 모델의 사이즈를 확인 할 수 있다.

@Test
void postEvent() throws Exception {
ResultActions result = mockMvc.perform(post("/events")
.param("name", "keesun")
.param("limit", "-10"))
.andExpect(status().isOk())
.andExpect(model().hasErrors());
ModelAndView mav = result.andReturn().getModelAndView();
Map<String, Object> model = mav.getModel();
System.out.print(model.size());
}

강의에서는 위에 처럼 테스트 코드를 작성하였지만 ResultActions의 인터페이스를 보니 andReturn 또한 정의 되어 있어 아래와 같이 테스트 코드를 변환할 수 있을 것 같아 테스트 해보니 같은 동작을 하였다.

@Test
void postEvent() throws Exception {
MvcResult mvcResult = mockMvc.perform(post("/events")
.param("name", "keesun")
.param("limit", "-10"))
.andExpect(status().isOk())
.andExpect(model().hasErrors())
.andReturn(); // 메서드 체이닝의 끝을 andReturn()으로 수정

ModelAndView mav = mvcResult.getModelAndView();
Map<String, Object> model = mav.getModel();
System.out.print(model.size());
}

출처: https://www.inflearn.com/course/%EC%9B%B9-mvc/dashboard


댓글을 작성해보세요.