Spring MVC3.x 支持 Junit测试Action

17 篇文章 0 订阅
4 篇文章 0 订阅

点击打开链接

JUnitActionBase类是所有JUnit的测试类的父类

1.package test;  
2.import javax.servlet.http.HttpServletRequest;  
3.import javax.servlet.http.HttpServletResponse;  
4.import org.junit.BeforeClass;  
5.import org.springframework.mock.web.MockServletContext;  
6.import org.springframework.web.context.WebApplicationContext;  
7.import org.springframework.web.context.support.XmlWebApplicationContext;  
8.import org.springframework.web.servlet.HandlerAdapter;  
9.import org.springframework.web.servlet.HandlerExecutionChain;  
10.import org.springframework.web.servlet.HandlerMapping;  
11.import org.springframework.web.servlet.ModelAndView;  
12.import org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter;  
13.import org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping;  
14./**  
15.* 说明: JUnit测试action时使用的基类 
16.*  
17.* @author  changlun.cheng
18.* @version 创建时间:   
19.*/   
20.public class JUnitActionBase {  
21.    private static HandlerMapping handlerMapping;  
22.    private static HandlerAdapter handlerAdapter;  
23.    /** 
24.     * 读取spring3 MVC配置文件 
25.     */  
26.    @BeforeClass  
27. public static void setUp() {  
28.        if (handlerMapping == null) {  
29.            String[] configs = { "file:src/springConfig/springMVC.xml" };  
30.            XmlWebApplicationContext context = new XmlWebApplicationContext();  
31.            context.setConfigLocations(configs);  
32.            MockServletContext msc = new MockServletContext();  
33.            context.setServletContext(msc);         context.refresh();  
34.            msc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context);  
35.            handlerMapping = (HandlerMapping) context  
36.                    .getBean(DefaultAnnotationHandlerMapping.class);  
37.            handlerAdapter = (HandlerAdapter) context.getBean(context.getBeanNamesForType(AnnotationMethodHandlerAdapter.class)[0]);     
38.        }  
39.    }  
40.  
41.    /** 
42.     * 执行request对象请求的action 
43.     *  
44.     * @param request 
45.     * @param response 
46.     * @return 
47.     * @throws Exception 
48.     */  
49.    public ModelAndView excuteAction(HttpServletRequest request, HttpServletResponse response)  
50. throws Exception {  
51.        HandlerExecutionChain chain = handlerMapping.getHandler(request);  
52.        final ModelAndView model = handlerAdapter.handle(request, response,  
53.                chain.getHandler());  
54.        return model;  
55.    }  
56.}  







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值