Search code examples
javacdideltaspikeopenwebbeans

@PersistenceContext is always null


I'm trying to get CDI (with Open Web Beans) working from within a unit test using Delta Spike (@RunWith(CdiTestRunner.class)). Dependency injection is working fine but my EntityManagerFactory is always null:

public class EntityManagerProducer {

    @PersistenceContext(unitName = "sbPersistenceUnit")
    private EntityManagerFactory emf;  //Always null

    @Produces
    public EntityManager create() {            
        return emf.createEntityManager();
    }

    public void close(@Disposes EntityManager em) {
        if (em.isOpen()) {
            em.close();
        }
    }
}

I know that my persistence.xml is okay because I can create the Session Factory manually:

EntityManagerFactory test = Persistence.createEntityManagerFactory("sbPersistenceUnit");

and all other injections are working fine. Does anybody know what might be missing?


Solution

  • In an unit-test you aren't in a managed environment. OpenWebBeans would support it via the openwebbeans-resource module + @PersistenceUnit, but that isn't portable. So you need to use e.g.:

    @Specializes
    public class TestEntityManagerProducer extends EntityManagerProducer {
        private EntityManagerFactory emf = Persistence.createEntityManagerFactory("...");
    
        @Produces
        //...
        @Override
        protected EntityManager create() {
            return emf.createEntityManager();
        }
    
        @Override
        protected void close(@Disposes EntityManager em) {
            if (em.isOpen()) {
                em.close();
            }
        }
    }
    

    in the test-classpath

    If you ask such questions on their mailing-list, you get answers petty quickly.