Skip to content
This repository has been archived by the owner on Nov 9, 2017. It is now read-only.

Commit

Permalink
Fix test problem by clearing hibernate cache in before and after method
Browse files Browse the repository at this point in the history
  • Loading branch information
Alex Eng committed Jun 28, 2012
1 parent 3912484 commit 6a8c45b
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions zanata-war/src/test/java/org/zanata/ZanataDbunitJpaTest.java
Expand Up @@ -8,6 +8,7 @@
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.dbunit.database.DatabaseConfig;
import org.dbunit.database.DatabaseConnection;
Expand All @@ -19,6 +20,10 @@
import org.dbunit.dataset.datatype.DefaultDataTypeFactory;
import org.dbunit.dataset.xml.FlatXmlDataSet;
import org.dbunit.operation.DatabaseOperation;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.persister.collection.AbstractCollectionPersister;
import org.hibernate.persister.entity.EntityPersister;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
Expand Down Expand Up @@ -87,14 +92,44 @@ public void prepareDataBeforeTest()
}

executeOperations(beforeTestOperations);
clearCache();
}

@AfterMethod
public void cleanDataAfterTest()
{
executeOperations(afterTestOperations);
clearCache();
}

private void clearCache()
{
Session session = getSession();
SessionFactory sessionFactory = session.getSessionFactory();

// Clear the Entity cache
Map classMetadata = sessionFactory.getAllClassMetadata();
for( Object obj : classMetadata.values() )
{
EntityPersister p = (EntityPersister)obj;
if( p.hasCache() )
{
sessionFactory.evictEntity( p.getEntityName() );
}
}

// Clear the Collection cache
Map collMetadata = sessionFactory.getAllCollectionMetadata();
for( Object obj : collMetadata.values() )
{
AbstractCollectionPersister p = (AbstractCollectionPersister)obj;
if( p.hasCache() )
{
sessionFactory.evictCollection( p.getRole() );
}
}
}

private void executeOperations(List<DataSetOperation> list)
{
IDatabaseConnection con = null;
Expand Down

0 comments on commit 6a8c45b

Please sign in to comment.