프로그래밍/Spring Framework

Spring 3.2 MockMvc

모지사바하 2013. 4. 25. 14:45

오늘 Spring 3.2의 MockMvc 를 살펴봤는데, 진짜 너무 너무 멋지다 훌륭하다..

컨트롤러 테스트는 이제 정말 편하게 할 수 있을 듯 하다.

junit testcase :

 

/**
 *
 */
package me.kwo2002.mvctemplate;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

/**
 * @author CHOI BIN
 *
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:test-servlet-context.xml")
@WebAppConfiguration
public class MockMvcTest {
 private final Logger logger = LoggerFactory.getLogger(getClass());
 private MockMvc mockMvc;
 
 @Autowired
 WebApplicationContext wac;
 
 @Before
 public void setUp() throws Exception {
  mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
 }

 @Test
 public void test() throws Exception{
  
  this.mockMvc.perform(get("/home/wel/{id}.json", "1").accept(MediaType.TEXT_HTML).characterEncoding("UTF-8"))
    .andDo(print())
    .andExpect(status().isOk())
    .andExpect(model().attributeExists("serverTime"));
 }
 
 }

 

결과 : JUNIT 테스트 성공

콘솔 :

MockHttpServletRequest:
         HTTP Method = GET
         Request URI = /home/wel/1.json
          Parameters = {}
             Headers = {Accept=[text/html]}

             Handler:
                Type = me.kwo2002.mvctemplate.HomeController
              Method = public java.lang.String me.kwo2002.mvctemplate.HomeController.home(java.util.Locale,org.springframework.ui.Model,java.lang.String)

  Resolved Exception:
                Type = null

        ModelAndView:
           View name = home
                View = null
           Attribute = serverTime
               value = April 25, 2013 2:27:47 PM KST
           Attribute = choibin
               value = {banana=바나나, grape=포도, apple=사과}

            FlashMap:

MockHttpServletResponse:
              Status = 200
       Error message = null
             Headers = {Content-Type=[application/json;charset=UTF-8], Pragma=[no-cache], Cache-Control=[no-cache, no-store, max-age=0], Expires=[1]}
        Content type = application/json;charset=UTF-8
                Body = {"choibin":{"banana":"바나나","grape":"포도","apple":"사과"},"serverTime":"April 25, 2013 2:27:47 PM KST"}
       Forwarded URL = null
      Redirected URL = null
             Cookies = []

콘솔이 정말 멋지지 않은가?? 너무 멋져서 감동 먹었다.. ㅎㅎ

요청. 응답에 대한 정보와,

Model 의 Attribute 정보,

 

위와 같이 콘솔에 멋진 로그를 찍으려면

.andDo(print())

딱 이거 하나면 된다. 정말 심플하지 않은가?

 

MockMvc 에 대한 더 자세한 정보를 알고 싶다면

http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/testing.html#spring-mvc-test-framework