junit 基于 spring 工程的测试基类编写

摘要: 无论是SSH,SSI架构,都少不了用spring, 但一般写后台程序的人都需要自己检测功能是否正确,数据是否正确,一般不会运行web  application 起来通过界面测试。都是直接通过 junit 写单元测试的, 但 通过 spring 配置的程序,需要拿到 配置的 bean 才可以。可以直接通过 ClassPathXmlApplicationContext 拿到beanFactory, 然后去获得各种bean. 这可以写一个基类,供其他测试类extend

无论是SSH,SSI架构,都少不了用spring, 但一般写后台程序的人都需要自己检测功能是否正确,数据是否正确,一般不会运行web application 起来通过界面测试。都是直接通过 junit 写单元测试的, 但 通过 spring 配置的程序,需要拿到 配置的 bean 才可以。可以直接通过 ClassPathXmlApplicationContext 拿到beanFactory, 然后去获得各种bean. 这可以写一个基类,供其他测试类extend:


public class BasicTest {
	@Before
	public void setUp() throws Exception {
		if (beanFactory == null) {
			beanFactory = new ClassPathXmlApplicationContext(
//			"com/hicom/platform/test/resources/context.xml");
					"classpath*:spring/context-web.xml");
		}
		if (sessionFactory == null) {
			sessionFactory = (SessionFactory) beanFactory
					.getBean("sessionFactory");
		}
		if (hibernateTemplate == null) {
			hibernateTemplate = (HibernateTemplate) beanFactory
					.getBean("hibernateTemplate");
		}
		if (session == null) {
			session = sessionFactory.openSession();
			//session = HibernateSessionFactory.getSession();
		}
		this.initialize();
	}

	

	protected static BeanFactory beanFactory;
	protected Session session;
	protected SessionFactory sessionFactory;
	protected HibernateTemplate hibernateTemplate;
}


其他测试类,只要继承这个基类,通过 beanFactory 得到自己想要的 bean , 然后调用方法就可以了。

上一篇: 在listener 中获取 spring context 从而得到 bean 的方法.
下一篇: python得到得到当前登录用户信息
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号