2

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?

StuPointerException
  • 7,117
  • 5
  • 29
  • 54

3 Answers3

1

You will need to use @PersistenceUnit to inject EntityManagerFactory. @PersistentContext is used for EntityManager injection.

Abhishek
  • 1,175
  • 1
  • 11
  • 21
1

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.

Dar Whi
  • 822
  • 5
  • 14
0

Do you define your entitymanagerFactory as a bean?

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> 
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>
mvlaicevich
  • 103
  • 1
  • 8