Spring集成Junit4单元测试

5 篇文章 0 订阅
1 篇文章 0 订阅
        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方法来对其他测试需要的资源进行管理。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值