Hibernation Tests - Reset Circuit
I am testing the CRUD operations of my DAOs in JUnit tests. When I do a single test, Hibernate always drops the schema and populates the DB in a known state. But when I run multiple tests in a row , Hibernate dumps the schema once and then the data accumulates while the tests are running.
This is unexpected behavior, so I would like to add a @Before
function to the tests method that explicitly resets the schema to avoid binding side data generated by previous tests during the chain of execution.
Any advice?
thanks
a source to share
First of all, what you are doing is not unit testing, but testiong integration.
Tips:
- Use transactions and rollback.
- Consider using DBUnit (not sure how useful that would be in your case).
- There is relevant code from here
org.springframework.orm.hibernate3.LocalSessionFactoryBean
.
...
Connection con = session.connection();
Dialect dialect = Dialect.getDialect(getConfiguration().getProperties());
String[] sql = getConfiguration().generateSchemaCreationScript(dialect);
executeSchemaScript(con, sql);
a source to share
You can start a transaction before and reverse the transaction on each method @Test
, something like this:
public class HibernateIntegrationTest {
protected static SessionFactory factory;
protected Session session;
@BeforeClass
public static void createSessionFactory() {
AnnotationConfiguration config = new AnnotationConfiguration();
// ...
config.configure();
factory = config.buildSessionFactory();
}
@AfterClass
public static void closeSessionFactory() {
if (factory != null) {
factory.close();
}
}
@Before
public void beginTransaction() {
session = factory.getCurrentSession();
session.beginTransaction();
}
@After
public void rollbackTransaction() {
if (session.getTransaction().isActive()) {
session.getTransaction().rollback();
}
if (session.isOpen()) {
session.close();
}
}
}
And extend this class in your test classes.
public class DemoTest extends HibernateIntegrationTest {
@Test
public void createMyEntity() {
MyEntity e = new MyEntity();
//...
session.save(e);
assertNotNull(e.getId());
}
}
Please note that this is not the cleanest way to do it, the above code is more for demonstration purposes.
a source to share