Class TestEntityMgrProvider

java.lang.Object
org.junit.rules.ExternalResource
uk.ac.ebi.utils.opt.orm.test.TestEntityMgrProvider
All Implemented Interfaces:
org.junit.rules.TestRule

public class TestEntityMgrProvider extends org.junit.rules.ExternalResource
A JPA EntityManager provider to be used in test classes as Rule (please see JUnit documentation for details). Before starting a test method in the test class using an instance of this provider, the EM will be initialised and it will be closed after the test is run (so, there will be one instantiation per test method). The class is supposed to be instantiated with some EM factory.

Typical Usage

 public class ExampleTest
 {
   @Rule
   public TestEntityMgrProvider emProvider = new TestEntityMgrProvider ( <your EntityManagerFactory here> );
   
   @Test
   public void testMethod () {
     EntityManager em = emProvider.getEntityManager ();
     <use em here>
   }
 }
 
date
Dec 13, 2011
Author:
Marco Brandizi
  • Constructor Details

    • TestEntityMgrProvider

      public TestEntityMgrProvider(javax.persistence.EntityManagerFactory emf)
      Pass me a factory that I can use to create entity managers.
  • Method Details

    • getEntityManager

      public javax.persistence.EntityManager getEntityManager()
      The last EM created by newEntityManager(). This is created by before() and disposed by after().
    • before

      protected void before() throws Throwable
      Uses the factor passed to constructor to create a new EntityManager, via newEntityManager(), makes it available via getEntityManager(). This is supposed to be done before each test method in a test class where an instance of this class is annotated with Rule.
      Overrides:
      before in class org.junit.rules.ExternalResource
      Throws:
      Throwable
    • after

      protected void after()
      Shuts down (flushes, closes, etc) the entity manager created by before(). This is supposed to be called by a test class via the Rule annotation.
      Overrides:
      after in class org.junit.rules.ExternalResource
    • newEntityManager

      public javax.persistence.EntityManager newEntityManager()
      Disposes (via after()) the previously created entity manager, if any, and creates a new entity manager, using the factory passed to the constructor. The method is public and returns the newly-created EM, cause sometimes you need to re-create a new EM in the middle of a test (eg, long tests that creates memory leaks).