使用了spring3 MVC后,给action做单元测试也很方便,我以前从来不给action写单元测试的,再在不同了,方便了,所以一定要写。
JUnitActionBase类是所有JUnit的测试类的父类
- package test;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.junit.BeforeClass;
- 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;
- /**
- * 说明: JUnit测试action时使用的基类
- *
- * @author 赵磊
- * @version 创建时间:2011-2-2 下午10:27:03
- */
- public class JUnitActionBase {
- private static HandlerMapping handlerMapping;
- private static HandlerAdapter handlerAdapter;
- /**
- * 读取spring3 MVC配置文件
- */
- @BeforeClass
- public static void setUp() {
- if (handlerMapping == null) {
- String[] configs = { "file:src/springConfig/springMVC.xml" };
- XmlWebApplicationContext context = new XmlWebApplicationContext();
- context.setConfigLocations(configs);
- MockServletContext msc = new MockServletContext();
- context.setServletContext(msc); context.refresh();
- msc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context);
- handlerMapping = (HandlerMapping) context
- .getBean(DefaultAnnotationHandlerMapping.class);
- handlerAdapter = (HandlerAdapter) context.getBean(context.getBeanNamesForType(AnnotationMethodHandlerAdapter.class)[0]);
- }
- }
- /** &