这是我的java类:
public class Finder { @PersistenceContext(unitName = "abc") EntityManager em; public boolean exists(int i) { return (this.em.find(Employee.class, i) != null); } }
这是单元测试:
public class FinderTest { @Test public void testSimple() { Finder f = new Finder(); assert(f.exists(1) == true); } }
测试失败,NullPointerException因为Finder.em没有任何人注入。我应该如何正确处理这种情况?是否存在最佳实践?
NullPointerException
Finder.em
如果没有像Spring这样的容器(或诸如基于Spring的Unitils之类的容器),则必须手动注入实体管理器。在这种情况下,您 可以 将以下内容用作基类:
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(); } } }