Clearing the entire database (for unit testing with Hibernate)

My unit tests use Hibernate to connect to the in-memory HSQLDB database. I was hoping there would be a way to clear and recreate the database (the entire database, including the schema and all data) in the JUnit TestCase.setUp() method.

+6
java unit-testing hibernate
source share
5 answers

you can configure the hibernate configuration file to force the database to recreate your tables and schemas each time.

 <!-- Drop and re-create the database schema on startup --> <property name="hbm2ddl.auto">create-drop</property> 

hibernate.hbm2ddl.auto Automatically checks or exports DDL schemas to the database when creating a SessionFactory. Using create-drop, the database schema will be deleted if the SessionFactory is explicitly closed.

eg. Check | update | create | create a fall

if you do not like to have this configuration in your actual sleep configuration, you can create one sleep configuration for unit testing purposes.

+7
source share
 hibernate.hbm2ddl.auto=create-drop 

And download the new SessionFactory .

+2
source share

If you use Spring, you can use the @Transactional attribute on your unit test, and by default at the end of each unit test all stored data will be automatically rolled back, so you do not need to worry about every change to the tables.

I missed an example here http://automateddeveloper.blogspot.com/2011/05/hibernate-spring-testing-dao-layer-with.html

+2
source share

Be careful wiping the world and starting a new one every time. Soon, you will most likely want to start with a โ€œstandardโ€ set of test data downloaded to your system. Thus, you really need to return to this basic state before starting each test. In this case, before each test, you want a Transaction that performs a rollsback .

To accomplish this, you must annotate your JUnit class:

 @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"classpath:/path/to/spring-config.xml"}) @TransactionConfiguration(transactionManager="myTransactionManager", defaultRollback=true) public class MyUnitTestClass { ... } 

And then annotate each of your test methods with @Transactional:

 @Transactional @Test public void myTest() { ... } 
+1
source share

From a testing point of view, it is best practice to clear the data after each individual test. If you use create-drop, it will also lose the table schema. This leads to overhead for reconstructing the circuit every time.

Since you are using hsql, which provides a direct mechanism for truncating, in this case it would be a better option.


 @After public void clearDataFromDatabase() { //Start transaction, based on your transaction manager dao.executeNativeQuery("TRUNCATE SCHEMA PUBLIC AND COMMIT"); //Commit transaction } 
0
source share

All Articles