I'm writing tests with JUnit for some methods operating on a test database.
I need to reset the database to the original state after each @Test
. I'm wondering what's the best way to do that.
Is there some method in the EntityManager
? Or should I just delete everything manually or with an SQL statement? Would it be better to just drop and recreate the whole database?
One technique that I have used in the past is to recreate the database from scratch by simply copying the database from a standard 'test database', and using this in the tests.
This technique works if:
This has the following advantages:
And the following disadvantages:
I use this with Oracle as the production/integration database and hsqldb as the test database. It works pretty well. hsqldb is a single file, so is easy to copy.
So, in the @Before, using hsqldb, you copy the file to a location such as target/it/database/name_of_test.script. This is picked up in the test.
In the @After, you delete the file (or just leave it, who cares). With hsqldb, you'll need to do a SHUTDOWN as well, so that you can delete the file.
You can also use a @Rule which extends from ExternalResource, which is a better way to manage your resources.
One other tip is that if you're using maven or something like it, you can create the database in target. I use target/it. This way, the copies of databases get removed when I do and mvn clean. For my batches, I actually copy all of my other properties files etc into this directory as well, so I don't get any files appearing in strange places either.
The easiest way is simply rolling back all changes after each test. This requires a transactional RDBMS and a custom test runner or similar that wraps each test into it's own transaction. Spring's AbstractTransactionalJUnit4SpringContextTests does exactly that.
DBUnit can reset your database between tests and even fill it with predefined test data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With