2009-08-11 51 views
0

我不確定在沒有準備好的內存數據庫的情況下測試我的數據庫的正確方法是什麼。我有以下用於JUnit4的TestSuite。單元測試PersistenceLayer(JPA/EclipseLink)

忽略JpaManager,我只是需要這個,因爲應用程序作爲Eclipse RCP運行而不是在一個容器中,也沒有使用Spring(但),所以我不能注入一個EntityManager引用並且必須手動處理它。

public class CustomerJpaTest { 

    private Customer testCustomer; 

    @Before 
    public void setUp() throws Exception { 
     JpaManager.getInstance().begin(); 
     // create a new user for testing 
     CustomerJpaDao dao = new CustomerJpaDao(); 
     testCustomer = new Customer(); 
     testCustomer.setName("Someone"); 
     dao.persist(testCustomer); 
     JpaManager.getInstance().commit(); 
    } 

    @After 
    public void tearDown() throws Exception { 
     // remove previously created user 
     CustomerJpaDao dao = new CustomerJpaDao(); 
     dao.remove(testCustomer); 
     JpaManager.getInstance().commit(); 
     JpaManager.getInstance().dispose(); 
    } 

    @Test 
    public void testCustomerSaving() throws Exception { 
     // not sure yet 
    } 

    @Test 
    public void testCustomerLoading() throws Exception { 
     ICustomerDao dao = new CustomerJpaDao(); 
     Customer customer = dao.findByName("Someone"); 
     assertEquals("Someone", customer.getName()); 
    } 
} 

因爲我在一個真正的數據庫上運行,我創造我的目標,我要在設置方法測試和測試(S)在完成後刪除它。 正是在這裏是我的問題:這setUp和tearDown實際上也可能是某種測試(testCustomerSaving,testCustomerDelete),但是當我測試運行在一個特定的順序,然後他們不會孤立(當保存失敗,加載失敗以及刪除)。

這樣做的正確方法是什麼?

回答

2

開始交易setUp並回滾交易tearDown

+0

這是在開始實際發生的事情和處置。但是由於我在存儲它之後做了一次提交,確實能夠從測試數據庫中加載它,所以回滾並沒有刪除該對象。可能這是一個錯誤的方式。如果只是從JPA緩存中加載項目,假設沒有區別,是否足以進行測試? – lostiniceland 2009-08-11 10:14:23

+1

然後,你不能偷工減料。在測試方法中,按照它們在實際用例/用戶故事中出現的順序進行調用。 – 2009-08-11 11:43:02

+0

您不需要提交就可以在同一個事務中查看來自查詢的持久數據 - 您只需要使用flush()來強制插入即可執行。然後,只要他們使用相同的底層連接,隨後的選擇就會看到該數據。 – wrschneider 2011-09-30 01:29:06