/sigmah/src/test/java/org/sigmah/test/MockHibernateModule.java

http://sigma-h.googlecode.com/ · Java · 75 lines · 53 code · 12 blank · 10 comment · 9 complexity · 5699061d2675cc1f84cf4804bad52518 MD5 · raw file

  1. /*
  2. * All Sigmah code is released under the GNU General Public License v3
  3. * See COPYRIGHT.txt and LICENSE.txt.
  4. */
  5. package org.sigmah.test;
  6. import java.io.File;
  7. import javax.persistence.EntityManager;
  8. import javax.persistence.EntityManagerFactory;
  9. import org.hibernate.ejb.Ejb3Configuration;
  10. import org.sigmah.server.dao.hibernate.HibernateModule;
  11. import org.sigmah.server.domain.PersistentClasses;
  12. import com.google.inject.Provider;
  13. import com.google.inject.Singleton;
  14. public class MockHibernateModule extends HibernateModule {
  15. private static EntityManagerFactory emf = null;
  16. @Override
  17. protected void configureEmf() {
  18. bind(EntityManagerFactory.class).toProvider(new Provider<EntityManagerFactory>() {
  19. @Override
  20. public EntityManagerFactory get() {
  21. // we are assuming that the tests do not affect the database schema, so there is no
  22. // need to restart hibernate for each test class, and we save quite a bit of time
  23. if (emf == null) {
  24. // clear out the default h2 databse if it exists
  25. File h2db = new File("activitityinfo-test.h2");
  26. if(h2db.exists()) {
  27. if(!h2db.delete()) {
  28. throw new RuntimeException("Could not delete the testing database activityinfo.h2 prior to starting tests. Maybe there is another" +
  29. " test running?");
  30. }
  31. }
  32. // we want to avoid a full scan of WEB-INF/classes during hibernate
  33. // startup for tests. So we avoid the normal persistence.xml config
  34. // and build the configuration manually.
  35. Ejb3Configuration cfg = new Ejb3Configuration();
  36. for(Class entityClass : PersistentClasses.LIST) {
  37. cfg.addAnnotatedClass(entityClass);
  38. }
  39. emf = cfg.configure(getConfigurationFilePath()) //add a regular hibernate.cfg.xml
  40. .buildEntityManagerFactory(); //Create the entity manager factory
  41. System.err.println("GUICE: EntityManagerFACTORY created");
  42. }
  43. return emf;
  44. }
  45. }).in(Singleton.class);
  46. }
  47. private String getConfigurationFilePath() {
  48. String db = "h2";
  49. if(System.getProperty("testDatabase") != null) {
  50. db = System.getProperty("testDatabase");
  51. }
  52. String cfgFile = "/hibernate-tests-" + db + ".cfg.xml";
  53. if( getClass().getResourceAsStream(cfgFile) == null ) {
  54. throw new Error("Cannot find hibernate cfg file for testing: " + cfgFile);
  55. }
  56. return cfgFile;
  57. }
  58. @Override
  59. protected void configureEm() {
  60. bind(EntityManager.class).toProvider(EntityManagerProvider.class)
  61. .in(TestScoped.class);
  62. }
  63. }