spring MVC junit 单元测试(controller)

新建一个基类:

package test;

/**
  *
*/


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.junit.Before;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.XmlWebApplicationContext;
import org.springframework.web.servlet.HandlerAdapter;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter;
import org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping;

/**
  * @author zbb
  *
*/
public class BaseTest<T> {
     public XmlWebApplicationContext ctx;
    

    private HandlerMapping handlerMapping;
     private HandlerAdapter handlerAdapter;

    /**
      * 容器初始化
      *
     * @author zbb
      * @throws Exception
      */
     @Before
     public void setUp() throws Exception {
         // change by xiaokang.zh
         String[] paths = { "file:WebContent/WEB-INF/temp-servlet.xml" };
         ctx = new XmlWebApplicationContext();
         ctx.setConfigLocations(paths);
         MockServletContext msc = new MockServletContext();
         ctx.setServletContext(msc);
         ctx.refresh();
         msc.setAttribute(
                 WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
                 ctx);
         handlerMapping = (HandlerMapping) ctx
                 .getBean(DefaultAnnotationHandlerMapping.class);
         handlerAdapter = (HandlerAdapter) ctx.getBean(ctx
                 .getBeanNamesForType(AnnotationMethodHandlerAdapter.class)[0]);
     }

    /**
      * 获取spring 的bean
      *
     * @author zbb
      * @param cl
      * @param name1
      * @return
      * @throws Exception
      */
     @SuppressWarnings("unchecked")
     protected T getBean(Class<T> cl, String... name1) throws Exception {
         String name = "";
         T t = null;
         if (name1 != null && name1.length > 0)
             name = name1[0];
         else {
             name = cl.getSimpleName();
             name = name.substring(0, 1).toLowerCase().concat(name.substring(1));
         }
         t = (T) ctx.getBean(name);
         return t;
     }

    /**
      * 用来进行Controller的测试,执行request对象的action 示例如下: 继承该类后,可以使用以下代码进行action的测试
      * request.setRequestURI("/order/add"); request.addParameter("id", "1002");
      * request.addParameter("date", "2010-12-30"); request.setMethod("POST");
      * final ModelAndView mav = this.excuteAction(request, response);//
      * 执行URI对应的action Assert.assertEquals("order/add", mav.getViewName());
      * String msg=(String)request.getAttribute("msg");
      *
     * @param request
      * @param reponse
      * @return
      * @throws Exception
      */
     protected ModelAndView excuteAction(HttpServletRequest request,
             HttpServletResponse response) throws Exception {
         HandlerExecutionChain chain = handlerMapping.getHandler(request);
         final ModelAndView model = handlerAdapter.handle(request, response,
                 chain.getHandler());
         return model;
     }
}


测试controller类

/**
  *
*/
package test;

import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;

import com.gangyi.crm.controller.SpringMVCtest;

/**
  * @author yangkun
  *
  */
public class ControllerTest extends BaseTest<SpringMVCtest> {
     public MockHttpServletRequest request;
     public MockHttpServletResponse response;
    
     @Before
     public void setUp() throws Exception{
         super.setUp();
         request=new MockHttpServletRequest();
         response=new MockHttpServletResponse();
     }
    
     @Test
     public void testTest(){
         request.setRequestURI("/springMVCtest.do");
         request.addParameter("method", "regist");
         request.setMethod("POST");
         try {
             this.excuteAction(request, response);
         } catch (Exception e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
         }
     }



}


点击》run as或debug as》juint测试


补充说明:

需要测试dao层时,若是dao层包nullpointException,有可能是你的数据库连接datasource使用代理或是其他,则需要重新在spring的配置文件配置bean id=datasource,

猜你喜欢

转载自zkf60553.iteye.com/blog/1604723