junit 基于 spring 工程的测试基类编写
By:Roy.LiuLast updated:2013-11-07
无论是SSH,SSI架构,都少不了用spring, 但一般写后台程序的人都需要自己检测功能是否正确,数据是否正确,一般不会运行web application 起来通过界面测试。都是直接通过 junit 写单元测试的, 但 通过 spring 配置的程序,需要拿到 配置的 bean 才可以。可以直接通过 ClassPathXmlApplicationContext 拿到beanFactory, 然后去获得各种bean. 这可以写一个基类,供其他测试类extend:
其他测试类,只要继承这个基类,通过 beanFactory 得到自己想要的 bean , 然后调用方法就可以了。
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 , 然后调用方法就可以了。
From:一号门
Next:python得到得到当前登录用户信息

COMMENTS