tags:

views:

285

answers:

1

Hello Everyone

I am not sure what is the correct way of testing my Database, without an prepared In-Memory-Database. I have following TestSuite for JUnit4.

Ignore the JpaManager, I just need this, because the application runs as a Eclipse RCP and not in a container, nor Spring is used (yet), so I cannot inject an EntityManager-reference and have to handle it manually.

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

Since I am running on a real database, I am creating my object that I am going to test in the setUp method and remove it after the test(s) are done. And exactly here is my problem: this setUp and tearDown could be actually also some kind of tests (testCustomerSaving, testCustomerDelete), but when I have the tests running in a particular order then they wont be isolated (when saving fails, loading fails as well, and then deleting).

What is the right way to do this?

+1  A: 

Begin a transaction in setUp and rollback the transaction in tearDown.

jeyoung
this is whats actually happening in begin and dispose. But since I am doing a commit after I store it to really be able to load it from the db in the test the rollback isnt deleting the object. Probably this is a wrong way. Would it be sufficient for the test if the oject is loaded just from the JPA-cache, assuming that there is no difference?
lostiniceland
Then, you cannot cut corners. In the test method, make the calls in the order that they will occur in the actual use-case/user story.
jeyoung