版權聲明:轉載時請以超鏈接形式標明文章原始出處和作者信息及本聲明
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.");
}
}
}