I\'m having a problem with injecting EntityManager by using @PersistenceContext. I try to inject EntityManager in EJB class with @PersistenceContext and I always get NullPointer
The EntityManager instance, is injected when the EJB is deployed in the Container. If you take a look at the lifecycle of enterprise bean, you will see clearly when dependency injection occurs. When the Container sees the @Persistencecontext annotation it will inject a container-managed EntityManager.
The problem is that the code executed in this test is not managed by the Container, therefore, no one inject the necessary dependencies.
bookDao = new BookEJB();
When you run the test, the BookEJB class is just a simple POJO, the @Stateless and @PersistenceContext annotations are simply ignored.
You have several alternatives in order to test your EJB, take a look at this link.