MockMvc
정의
•
가짜 객체를 생성하여 애플리케이션 서버에 배포하지 않고도 스프링 MVC 동작을 재현할 수 있는 유틸리티 클래스
사용
@WebMvcTest(ArticleRestController.class)
class ArticleRestControllerTest {
@Autowired
MockMvc mockMvc;
@MockBean
ArticleService articleService;
@Test
@DisplayName("해당 id의 글이 조회가 잘 되는지")
void findSingle() throws Exception {
Long id = 1l;
given(articleService.getArticleById(id))
.willReturn(new ArticleDto(1l, "첫번째 글", "내용입니다."));
mockMvc.perform(get("/api/v1/articles/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").exists())
.andExpect(jsonPath("$.title").exists())
.andExpect(jsonPath("$.content").exists())
.andDo(print());
verify(articleService).getArticleById(id);
}
}
Java
복사
요청 설정 메소드
•
param / params : 쿼리 스트링 설정
•
cookie : 쿠키 설정
•
content : 요청 본문 설정
•
header / headers : 요청 헤더 설정
•
contentType : 본문 타입 설정
@Test
public void testController() throws Exception{
mockMvc.perforem(get("test"))
.param("name", "최민준")
.cookie("쿠키 값")
.header("헤더 값:)
.contentType(MediaType.APPLICATION.JSON)
.content("json으로");
}
Java
복사
검증 메소드
•
status : 상태 코드 검증
•
header : 응답 header 검증
•
content : 응답 본문 검증
•
cookie : 쿠키 상태 검증
•
view : 컨트롤러가 반환한 뷰 이름 검증
•
redirectedUrl(Pattern) : 리다이렉트 대상의 경로 검증
•
model : 스프링 MVC 모델 상태 검증
•
request : 세션 스코프, 비동기 처리, 요청 스코프 상태 검증
•
forwardedUrl : 이동대상의 경로 검증
•
jsonPath: 해당하는 값이 존재하는지
•
verify: • 해당 메서드가 실행됐는지를 검증
@Test
public void testController() throws Exception{
mockMvc.perform(get("test"))
.param("name", "최민준")
.cooke("쿠키 값")
.header("헤더 값:)
.contentType(MediaType.APPLICATION.JSON)
.content("json으로")
.andExpect(status().isOk()) // 여기부터 검증
.andExpect(content().string("expect json값"))
.andExpect(view().string("뷰이름"));
}
Java
복사
요청 설정 메소드
기타 메소드
•
andDo() : print, log를 사용할 수 있는 메소드
•
print() : 실행결과를 지정해준 대상으로 출력, default = System.out
•
log() : 실행결과를 디버깅 레벨로 출력, 레벨은 org.springframework.test.web.servlet.result
@Test
public void testController() throws Exception{
mockMvc.perform(get("test"))
.param("name", "최민준")
.cooke("쿠키 값")
.header("헤더 값:)
.contentType(MediaType.APPLICATION.JSON)
.content("json으로")
.andExpect(status().isOk()) // 여기부터 검증
.andExpect(content().string("expect json값"))
.andExpect(view().string("뷰이름"));
.andDo(print()) //여기부터 기타 메소드
.andDo(log());
}
Java
복사