views:

59

answers:

2

I want to cleanup the database after every test case without rolling back the transaction. I have tried DBUnit's DatabaseOperation.DELETE_ALL, but it does not work if a deletion violates a foreign key constraint. I know that I can disable foreign key checks, but that would also disable the checks for the tests (which I want to prevent).

I'm using JUnit 4, JPA 2.0 (Eclipselink), and Derby's in-memory database. Any ideas?

Thanks, Theo

A: 

I am a bit confused as DBUnit will reinitialize the database to a known state before every test.

They also recommend as a best practice not to cleanup or otherwise change the data after the test.

So if it is cleanup you're after to prepare the db for the next test, I would not bother.

Peter Tillemans
Actually, I'm not using the DBUnit. I just tried the mentioned DELETE_ALL operation. I'm filling my database in a JUnit @Before method. Is DBUnit a perfect fit with JPA?
Theo
I use Unitils which is a rapper around dbunit. You create a dataset with the stuff you care about (in xml : nobody is perfect), add a couple of annotations to your testclass and you're done. See : http://www.unitils.org/tutorial.html#Testing_with_JPA
Peter Tillemans
+1  A: 

Yes, in-transaction test would make your life much easier, but if transaction is your thing then you need to implement compensating transaction(s) during cleanup (in @After). It sounds laborious and it might be but if properly approached you may end up with a set of helper methods (in tests) that compensate (cleanup) data accumulated during @Before and tests (using JPA or straight JDBC - whatever makes sense).

For example, if you use JPA and call create methods on entities during tests you may utilize (using AOP if you fancy or just helper test methods like us) a pattern across all tests to:

  1. track ids of all entities that have been created during test
  2. accumulate them
  3. replay entity deletes for these entities in right order in @After
grigory