-
[SPRING] mockMvc 유닛 테스트Spring/spring framework 기본 및 이론 2020. 6. 16. 18:44
mockMvc 사용준비
@Autowired SampleController sampleController; private MockMvc mockMvc; @Before public void 기본() throws Exception{ mockMvc = MockMvcBuilders.standaloneSetup(sampleController).build(); }
기본 get 방식 test
@Test public void get_sample() throws Exception{ RequestBuilder reqBuilder = MockMvcRequestBuilders.get("/test" + 1) .param("param1", param1) .param("param2", param2) .param("param3", param3); this.mockMvc.perform(reqBuilder).andExpect(status().isOk()).andDo(print()); }
post @requestBody 요청
public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); @Test public void 제이슨_바디리퀘스트() throws Exception{ RequestBuilder reqBuilder = MockMvcRequestBuilders.post("/test/" + 1) .header("header1", header1) .header("header2" , header2) .contentType(APPLICATION_JSON_UTF8) .content(requestJson); this.mockMvc.perform(reqBuilder).andExpect(status().isOk()).andDo(print()); }
메소드 사용법
andDO
요청에 대한 처리를 합니다. print() 메소드가 일반적입니다.
.andDo(print())
andExpert
예상값을 검증합니다. assert* 메소드들과 유사합니다.
// status 값이 정상인 경우를 기대하고 만든 체이닝 메소드 중 일부입니다. .andExpect(status().isOk()) // contentType을 검증합니다. .andExpect(content().contentType("application/json;charset=utf-8"))
andReturn
테스트 클래스에서 작성은 안했지만 테스트한 결과 객체를 받을 때 사용합니다.
MvcResult result = this.mockMvc.perform(get("/")) .andDo(print()) .andExpect(status().isOk()) .andExpect(model().attributeExists("serverTime")) .andReturn();
반응형'Spring > spring framework 기본 및 이론' 카테고리의 다른 글
[SPRING] SPEL 스프링 표현식 (0) 2021.02.08 [Spring] 스프링 어플리케이션 kill 시키기 (0) 2020.09.27 [Spring] 스프링 mybatis transactions (0) 2020.06.02 [Spring] 스프링 mapper 등록하기 (0) 2020.06.02 [Spring] Mybatis SqlSessionFactory 란 (0) 2020.06.01