📄 abstracttest.java
字号:
package sample.test;
import junit.framework.TestCase;
import org.hibernate.FlushMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.orm.hibernate3.SessionHolder;
import org.springframework.transaction.support.TransactionSynchronizationManager;
/**
*
* @author limq
*有时候还是需要测试多个session的时候,所以多加了一个newSession()的方法
*如果有需要用到多个session的时候:
public void testAbc() {
context.getBean("service").foo();
newSession();
context.getBean("service").bar();
}
*/
public abstract class AbstractTest extends TestCase {
protected ApplicationContext context;
protected void setUp() throws Exception {
context = getContext();
openSession();
super.setUp();
}
// protected abstract ApplicationContext getContext();
private void openSession() {
SessionFactory sessionFactory = (SessionFactory) context.getBean("sessionFactory");
Session hibSession = SessionFactoryUtils.getSession(sessionFactory, true);
hibSession.setFlushMode(FlushMode.NEVER);
TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(hibSession));
}
protected void newSession() {
closeSession();
openSession();
}
protected void tearDown() throws Exception {
super.tearDown();
closeSession();
}
private void closeSession() {
SessionFactory sessionFactory = (SessionFactory) context.getBean("sessionFactory");
SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.unbindResource(sessionFactory);
SessionFactoryUtils.closeSessionIfNecessary(sessionHolder.getSession(), sessionFactory);
}
protected ApplicationContext getContext() {
String[] paths = {"/applicationContext-basic.xml","/applicationContext-security-acegi.xml","/application.xml"};
ApplicationContext ctx = new ClassPathXmlApplicationContext(paths);
return ctx;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -