2010-09-27 64 views
8

這是我的java類:如何在單元測試期間注入PersistenceContext?

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); 
    } 
} 

測試失敗以來Finder.emNullPointerException是任何人都無法注入。我應該如何正確處理這種情況?是否存在最佳實踐?

回答

7

沒有像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(); 
     } 
    } 
} 
3

這取決於什麼你想測試。當您在Finder課程中有複雜的業務邏輯時,您可能需要模擬EntityManager - 使用模擬框架(如EasyMockMockito) - 以便單元測試該邏輯。

現在既然不是這種情況,我懷疑你想測試Employee實體的持久性(這通常被稱爲集成測試)。這需要使用數據庫。爲了簡化測試並保持測試的便攜性,您可以使用內存數據庫(如HSQLDB)來實現此目的。爲了啓動HSQLDB,創建一個持久化上下文並將這個上下文注入Finder類,建議使用IoC框架如Spring

在互聯網上有大量的教程解釋如何使用JPA/Spring/HSQLDB。看看這個示例項目:Integration testing with Maven 2, Spring 2.5, JPA, Hibernate, and HSQLDB

+0

我在每一個單元測試來做到這一點注射「手動」,對不對? – yegor256 2010-09-27 21:00:13

+0

沒有Spring可以解析@PersistenceContext註解並將它注入到Finder類中。您只需引用FinderTest中的ApplicationContext。 – 2010-09-27 21:02:32

相關問題