主要步骤
1. 在工程的pom文件中增加spring-test的依赖:
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency>
2. 使用springframework提供的单元测试
新建测试类,并在该类上加上两个注解:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"classpath*:ApplicationContext.xml"})
@RunWith 大家并不陌生,junit4里用它来做junit加载器
@ContextConfiguration 主要用来加载spring的配置文件路径:是一个字符串数组,可以加载多个spring配置文件
测试代码如下:
1 import static org.junit.Assert.assertEquals; 2 3 import org.junit.Test; 4 import org.junit.runner.RunWith; 5 import org.springframework.beans.factory.annotation.Autowired; 6 import org.springframework.context.ApplicationContext; 7 import org.springframework.test.context.ContextConfiguration; 8 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 9 10 @RunWith(SpringJUnit4ClassRunner.class) 11 @ContextConfiguration(locations = {"classpath:ApplicationContext.xml"}) 12 public class EmpolyeeTest { 13 @Autowired 14 ApplicationContext ctx; 15 16 @Test 17 public void testEmployee(){ 18 Employee employee =(Employee) ctx.getBean("employee"); 19 assertEquals("zhangsan",employee.getName()); 20 } 21 22 }
3. 封装基于AbstractJUnit4SpringContextTests的测试基类
1 import org.junit.Test; 2 import org.junit.runner.RunWith; 3 import org.springframework.context.ApplicationContext; 4 import org.springframework.test.context.ContextConfiguration; 5 import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; 6 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 7 8 @RunWith(SpringJUnit4ClassRunner.class) 9 @ContextConfiguration(locations={"classpath*:ApplicationContext.xml"}) 10 public class SpringTest extends AbstractJUnit4SpringContextTests { 11 12 13 public <T> T getBean(Class<T> type){ 14 return applicationContext.getBean(type); 15 } 16 17 public Object getBean(String beanName){ 18 return applicationContext.getBean(beanName); 19 } 20 protected ApplicationContext getContext(){ 21 return applicationContext; 22 }
然后其他测试类只需要继承该类即可,可以省去每次都要绑定Application对象。
4. 当项目变得复杂,其中的spring配置文件被拆分成了多个,这样该如何引入多个配置文件呢?如下:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath*:spring-ctx-service.xml", "classpath*:spring-ctx-dao.xml" })
这样就可以轻松的引入多个spring的配置文件了。或者配置符合某一个正则表达式的一类文件,如:
1 @RunWith(SpringJUnit4ClassRunner.class) 2 @ContextConfiguration(locations = "classpath*:spring-ctx-*.xml")