Search code examples
unit-testingjpajpa-2.0dbunit

JPA - How to truncate tables between unit tests


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


Solution

  • Simple: Before each test, start a new transaction and after the test, roll it back. That will give you the same database that you had before.

    Make sure the tests don't create new transactions; instead reuse the existing one.