Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setup and Tear Down of Complex Database State With Hibernate / Spring / JUnit

I have a class I'm unit testing that requires fairly extensive database setup before the individual test methods can run. This setup takes a long time: for reasons hopefully not relevant to the question at hand, I need to populate the DB programatically instead of from an SQL dump.

The issue I have is with the tear-down. How can I easily rollback all the changes made in the db setup phase?

I'm currently using Hibernate + Spring Transactional Testing support, such that my individual test methods are wrapped in transactions.

One solution would be to do the db setup within each test method, such that the db setup would be rolled back automatically. However, the test methods would take forever to run since each method would need to re-prep the database.

Any other ideas? Basically, I'm looking for a way to run my db setup, run my individual tests (each wrapped in a transaction which gets rolled-back after execution), and then roll-back the initial db setup. Any ideas on making this working in a Hibernate / Spring / Junit fashion? Is there a Hibernate "drop all tables" equivalent command?

like image 741
Brian Ferris Avatar asked May 05 '09 01:05

Brian Ferris


1 Answers

Are you stuck with a specific database vendor? If not, you could use an in-memory database, such as HSQLDB. When you are done with the tests you just throw away the state. This is only appropriate if the tables can be empty at the start of the test suite (before your programmatic setup, that is).

You still need to create tables, but if everything is neatly mapped using Hibernate you can use the hbm2ddl to generate your tables. All you have to do is add the following to your test session factory definition:

<session-factory>
    ...
    <property name="hibernate.hbm2ddl.auto">create</property>
    ...
</session-factory>

If this solution seems applicable I can elaborate on it.

like image 72
waxwing Avatar answered Oct 20 '22 17:10

waxwing