在进行springmvc的开发中有时候进行单元测试又不想去启动服务器,spring提供了AbstractContextLoader可以让我们手动的加载xxx-servlet.xml文件:
1.首先建立一个模仿类
import javax.servlet.ServletContext; import org.springframework.beans.factory.support.BeanDefinitionReader; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.AnnotationConfigUtils; import org.springframework.core.io.FileSystemResourceLoader; import org.springframework.mock.web.MockServletContext; import org.springframework.test.context.support.AbstractContextLoader; import org.springframework.web.context.support.StaticWebApplicationContext; public class MockServletContextWebContextLoader extends AbstractContextLoader { private static final String SERVLET_CONTEXT_WEB_ROOT = "/webapp"; @Override public final ConfigurableApplicationContext loadContext(String... locations) throws Exception { /* * Use a type which implements ConfigurableWebApplicationContext! */ StaticWebApplicationContext context = new StaticWebApplicationContext(); prepareContext(context); customizeBeanFactory(context.getDefaultListableBeanFactory()); createBeanDefinitionReader(context).loadBeanDefinitions(locations); AnnotationConfigUtils.registerAnnotationConfigProcessors(context); customizeContext(context); context.refresh(); context.registerShutdownHook(); return context; } protected void prepareContext(StaticWebApplicationContext context) { /* * Incorporate mock servlet context! */ ServletContext servletContext = new MockServletContext(SERVLET_CONTEXT_WEB_ROOT, new FileSystemResourceLoader()); servletContext.setAttribute(StaticWebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context); context.setServletContext(servletContext); } protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory) { } protected BeanDefinitionReader createBeanDefinitionReader(StaticWebApplicationContext context) { return new XmlBeanDefinitionReader(context); } protected void customizeContext(StaticWebApplicationContext context) { } @Override protected String getResourceSuffix() { return "-servlet.xml"; } }
2.编写测试类
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** *把测试交给Spring框架自己来做,继承AbstractJUnit4SpringContextTests *并指定配置文件的路径 */ @ContextConfiguration(inheritLocations = true, loader = MockServletContextWebContextLoader.class,locations = { "file:src/main/webapp/WEB-INF/xxx-servlet.xml"}) @RunWith(SpringJUnit4ClassRunner.class) public class TestBase extends AbstractJUnit4SpringContextTests { // 依赖注入 public @Autowired XxxClass test; @Test public void test() { // TODO // test.xxx(); } }