2009-08-11 45 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