主要步骤:
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配置文件
测试代码如下:
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:ApplicationContext.xml"})
public class EmpolyeeTest {
@Autowired
ApplicationContext ctx;
@Test
public void testEmployee(){
Employee employee =(Employee) ctx.getBean("employee");
assertEquals("zhangsan",employee.getName());
}
}
3.封装基于AbstractJUnit4SpringContextTests的测试基类
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath*:ApplicationContext.xml"})
public class SpringTest extends AbstractJUnit4SpringContextTests {
public <T> T getBean(Class<T> type){
return applicationContext.getBean(type);
}
public Object getBean(String beanName){
return applicationContext.getBean(beanName);
}
protected ApplicationContext getContext(){
return applicationContext;
}
然后其他测试类只需要继承该类即可,可以省去每次都要绑定Application对象。
4.当项目变得复杂,其中的spring配置文件被拆分成了多个,这样该如何引入多个配置文件呢?如下:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath*:spring-ctx-service.xml", "classpath*:spring-ctx-dao.xml" })
这样就可以轻松的引入多个spring的配置文件了。
或者配置符合某一个正则表达式的一类文件,如:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath*:spring-ctx-*.xml")