版权声明:转载时请以超链接形式标明文章原始出处和作者信息及本声明
http://ralf0131.blogbus.com/logs/55701639.html
参考:http://www.javaeye.com/topic/14631
关于JUnit4: http://www.ibm.com/developerworks/cn/java/j-junit4.html
背景:
如果在Hibernate层采用lazy=true的话,有的时候会抛出LazyInitializationException,这时一种解决办法是用OpenSessionInViewFilter,但是如果通过main方法来运行一些测试程序,那么上述方法就没有用武之地了。这里提供了一种方法,来达到实现和OpenSessionInViewFilter相同作用的目的。这里的应用场景是采用JUnit4来编写测试用例。
JUnit4的好处是:采用annotation来代替反射机制,不必写死方法名.
首先添加一个abstract class(AbstractBaseTestCase.class), 做一些准备性的工作:
(可以看到@Before和@After两个annotation的作用相当于setUp()和tearDown()方法,但是,显然更灵活)
package testcase;
import org.hibernate.FlushMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.After;
import org.junit.Before;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.orm.hibernate3.SessionHolder;
import org.springframework.transaction.support.TransactionSynchronizationManager;
/***
* An abstract base class for TestCases.
* All test cases should extend this class.
*/
public class AbstractBaseTestCase {
private SessionFactory sessionFactory;
private Session session;
protected FileSystemXmlApplicationContext dsContext;
private String []configStr = {"/WebRoot/WEB-INF/applicationContext.xml"};
@Before
public void openSession() throws Exception {
dsContext = new FileSystemXmlApplicationContext(configStr);
sessionFactory = (SessionFactory) dsContext.getBean("sessionFactory");
session = SessionFactoryUtils.getSession(sessionFactory, true);
session.setFlushMode(FlushMode.MANUAL);
TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
}
@After
public void closeSession() throws Exception {
TransactionSynchronizationManager.unbindResource(sessionFactory);
SessionFactoryUtils.releaseSession(session, sessionFactory);
}
}
接下来继承上述基类,实现测试逻辑:
(注意import static用于引用某个类的静态方法)
(@Test注解表明该方法是一个测试方法)
package testcase;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.Before;
import org.junit.Test;
public class testCase1 extends AbstractBaseTestCase {
private YourManager manager;
@Before
public void prepare(){
manager = (YourManager)dsContext.getBean("YourManager");
}
@Test
public void test1(){
try {
String result = manager.do_sth();
System.out.println(result);
assertEquals(result, EXPECTED_RESULT);
} catch (Exception e) {
e.printStackTrace();
fail("Exception thrown.");
}
}
}