主要步骤:
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")
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论