如何在单元测试期间注入PersistenceContext?

yeg*_*256 15 java orm hibernate jpa

这是我的java类:

public class Finder {
  @PersistenceContext(unitName = "abc")
  EntityManager em;
  public boolean exists(int i) {
    return (this.em.find(Employee.class, i) != null);
  }
}
Run Code Online (Sandbox Code Playgroud)

这是单元测试:

public class FinderTest {
  @Test public void testSimple() {
    Finder f = new Finder();
    assert(f.exists(1) == true);
  }
}
Run Code Online (Sandbox Code Playgroud)

测试失败,NullPointerException因为Finder.em没有人注入.我该如何妥善处理这种情况?有没有最佳实践?

Pas*_*ent 13

如果没有像Spring这样的容器(或像Unitils这样的容器 - 基于Spring),则必须手动注入实体管理器.在这种情况下,您可以使用类似这样的基类:

public abstract class JpaBaseRolledBackTestCase {
    protected static EntityManagerFactory emf;

    protected EntityManager em;

    @BeforeClass
    public static void createEntityManagerFactory() {
        emf = Persistence.createEntityManagerFactory("PetstorePu");
    }

    @AfterClass
    public static void closeEntityManagerFactory() {
        emf.close();
    }

    @Before
    public void beginTransaction() {
        em = emf.createEntityManager();
        em.getTransaction().begin();
    }

    @After
    public void rollbackTransaction() {   
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }

        if (em.isOpen()) {
            em.close();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)