Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why EntityManager is not injected?

Tags:

java

jpa

This is the class I'm trying to test:

@Stateless
public class Finder {
  @PersistenceContext(unitName = "abc")
  EntityManager em;
  public String read(int i) {
    return this.em.find(Employee.class, i).getName();
  }
}

This is the unit test:

public class FinderTest {
  @Test public void testReadingWorks() {
    Finder f = new Finder();
    String name = f.find(1);
    assert(name.length() > 0);
  }
}

The problem is that EntityManager is not injected, and is NULL during testing. What am I doing wrong?

ps. Actually, I don't understand who exactly is going to inject EntityManager. The unit test is started by JUnit, outside of any container... Maybe I have to inject em manually in the test?

like image 443
yegor256 Avatar asked Oct 05 '10 09:10

yegor256


1 Answers

Injection of EntityManagers only works in managed beans, since you are creating the Finder with new no container is involved. You could eithere create the EntityManager yourself using the EntityManagerFactory or use a embeddable Container like OpenEJB in your unit tests.

like image 72
Jörn Horstmann Avatar answered Sep 28 '22 14:09

Jörn Horstmann