user1802311
user1802311

Reputation: 71

How to reload database data in junit test fastly?

I develop an application in Java with Spring and Hibernate. And now I am looking for a solution for fast reloading data between tests. The tests require a lot of data, which are generated and persisted through services. As a db I use hsqldb in memory. Data generating process takes about 30 seconds, so it is too long to simply run it before each test.

So I was wondering if it is good idea and if it is possible with hsqldb to run data loader once at the begining of test case or suite, then create a dump and restore it before each test? I can't find how to create dump in hsqldb, especially if it is in memory db.

I appreaciate all yours help.

EDIT: I have to use database. Let's consider that they re integration tests.

Upvotes: 0

Views: 1827

Answers (3)

fredt
fredt

Reputation: 24372

You can use an HSQLDB file: database with the default MEMORY tables.

After generating the dataset, add the property files_readonly=true to the database.properties file. You then run the tests with this database. This ensures your tests run and modify the data the same way as a mem: database, but the changes made by the tests are not persisted when the test process ends. The original data is loaded in a few seconds in the fastest possible way.

Upvotes: 1

Jan Hruby
Jan Hruby

Reputation: 1497

try using this annotation in your test class

@TransactionConfiguration(transactionManager="nameOfYourTransactionManager", defaultRollback=true)

I found it here

Upvotes: 0

dkatzel
dkatzel

Reputation: 31658

You can use dbUnit to load and clean the database before and after each test but I don't think that will improve your performance.

Instead, I would ask why you need so much data for a unit test? 30 seconds isn't too bad for an integration test that actually hits a database, but I think you should strive to have unit tests that don't hit the database at all and instead use mock objects to simulate interacting with your services. Then you can have a few integration tests that actually use a database but those tests won't have to cover all scenarios since your faster unit tests should do that already.

Upvotes: 1

Related Questions