
Originally Posted by
Martin Kersten
The db and the session are initialized using:
Code:
getSession().clear();
getLocalSessionFactoryBean().createDatabaseSchema();
I found this idea interesting, so I tried implementing a base test class, as follows:
Code:
import net.sf.hibernate.Session;
import org.springframework.orm.hibernate.HibernateTransactionManager;
import org.springframework.orm.hibernate.LocalSessionFactoryBean;
import org.springframework.orm.hibernate.SessionFactoryUtils;
import org.springframework.test.AbstractDependencyInjectionSpringContextTests;
public abstract class BaseTestCase
extends AbstractDependencyInjectionSpringContextTests
{
protected void onSetUp() throws Exception
{
HibernateTransactionManager txMgr = (HibernateTransactionManager)
applicationContext.getBean("transactionManager");
Session session = SessionFactoryUtils.getSession(txMgr.getSessionFactory(), true);
if (session != null)
{
session.clear();
}
LocalSessionFactoryBean sessionFactoryBean = (LocalSessionFactoryBean)
applicationContext.getBean("sessionFactory");
sessionFactoryBean.createDatabaseSchema();
}
}
The corresponding applicationContext.xml has the following relevant lines in it:
Code:
<bean id="sessionFactory" class="org.springframework.orm.hibernate.LocalSessionFactoryBean">
<property name="dataSource">
<ref local="dataSource"/>
</property>
<!-- some stuff ommitted for brevity-->
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate.HibernateTransactionManager">
<property name="sessionFactory"><ref local="sessionFactory"/></property>
</bean>
Here's a concrete test case:
Code:
public class TestStoreFacade extends BaseTestCase
{
private StoreFacade storeFacade;
protected void onSetUp() throws Exception
{
super.onSetUp();
storeFacade = (StoreFacade) applicationContext.getBean("storeFacade");
}
public void testSomething()
{
Item item = storeFacade.createItem("foo");
assertNotNull(item);
}
protected String[] getConfigLocations()
{
return new String[] {"applicationContext.xml"};
}
}
In theory that should work, but for some reason I get a ClassCastException on this line of BaseTestCase:
Code:
LocalSessionFactoryBean sessionFactoryBean = (LocalSessionFactoryBean)
applicationContext.getBean("sessionFactory");
It claims that the object that I think is of type LocalSessionFactoryBean is in fact of type net.sf.hibernate.impl.SessionFactoryImpl. Yet, that's now how it is declared in the applicationContext.xml file.
Does anyone know what is going on here, and how I can get an instance of LocalSessionFactoryBean?