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.}