Spring集成Junit单元测试有两种方式,一种是引入spring-test等相关包,另一种是直接使用junit。本文只介绍第二种方式,此方式的优点是不需要引入额外的spring-test包,缺点是需要手动调用方法来获得实例。
import org.junit.After;
import org.junit.Before;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public abstract class BaseTest {
protected ClassPathXmlApplicationContext context;
/**
* 加载xml文件
* @param springXmlpath
*/
private void loadBeans(String springXmlpath){
if(springXmlpath==null||springXmlpath.replaceAll(" ","").length()==0){
System.err.println("spring xml path can not be null");
System.exit(-1);
}
if(context==null){
context = new ClassPathXmlApplicationContext(springXmlpath.split("[;\\s]+"));
context.start();
}
}
/**
* 子类重写后可在加载完xml文件后,进行其他的初始化操作
*/
protected void init(){
}
@Before
public void setUp() throws Exception {
loadBeans(getSpringXmlpath());
init();
}
/**
* 子类重写后可在销毁context实例后,进行其他资源的释放操作
*/
protected void destroy(){
}
@After
public void tearDown() throws Exception {
context.destroy();
destroy();
}
/**
* 获取spring xml文件路径
* @return spring xml文件路径
*/
protected abstract String getSpringXmlpath();
protected <T> T getBean(Class<T> calzz){
return context.getBean(calzz);
}
@SuppressWarnings("unchecked")
protected <T> T getBean(String beanid){
return (T)context.getBean(beanid);
}
}
其他测试类继承BaseTest即可,可以通过重写init与destroy方法来对其他测试需要的资源进行管理。