SpringFramework/JUnit Test

MockMvc get post 테스트

lovineff 2021. 5. 18. 11:28

MockMvc를 통한 Get, Post 테스트 방법을 소개한다.

 

Get

// 리스트, 객체등을 쉽게 전달하기 위해서 MultiValueMap을 사용한다.
MultiValueMap<String, String> multiValueMap = new LinkedMultiValueMap<>();
multiValueMap.put("articleId", articleIdList);  // 리스트 변환 없이 전달가능

MockHttpServletResponse response = mockMvc.perform(
                get("/data/getManageDebateList")
                // PathVariable 응답 URL 작성
                // get("/news/detail/hotissue/{menuId}/{id}", menuId, id)
                .params(multiValueMap)
                // param(String) 으로 사용해도되나 String으로 변환해야하는 불편함이 있다.
        )
        .andExpect(status().isOk())
        .andDo(print())
        .andReturn()
        .getResponse();

 

Post

List<String> ids = Arrays.asList("a","b","c","d","e");
Gson gson = new Gson();

// Map 대신 객체를 사용해도 된다.
Map<String, Object> map = new HashMap<>();
map.put("ids", ids);

String json = gson.toJson(map);

MvcResult mvcResult = mockMvc.perform(get("/community/getTopAd"))
        .andExpect(status().isOk())
        .andExpect(content().contentType("text/plain;charset=UTF-8"))
//      .andExpect(content().contentType(MediaType.APPLICATION_JSON))
        .andExpect(content().encoding(CharEncoding.UTF_8))
//      .andExpect(jsonPath("$.idx").value(34))   // jsonPath를 사용하여 json값에 원하는 키,값이 있는지 확인
        // model()은 ModelAndView attribute 응답값 검사에 사용
//      .andExpect(model().size(1))
//      .andExpect(model().attributeExists("idx"))
//      .andExpect(model().attributeExists("subject"))
        .andDo(print())
        .andReturn();

 

 

model().attributeExists() 관련 로직 정리

해당 함수는 Controller에서 Model 응답시 Model에 addAttribute한 값 존재여부 검사

 

Controller

model에 값 추가

Test 코드

model에 원하는 값 존재여부 검사

Mock 컨트롤러 호출 결과 로그

ModelAndView에 Controller에서 addAttribute한 값이 존재하는것을 확인할 수 있다.

Front에 원하는 값이 전달되는지 확인이 가능하다.