My unit tests use Hibernate to connect to an 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 the data) in JUnit's TestCase.setUp() method.
-
3If you are testing your DB, then imo it isn't unit testing.Jamie– Jamie2010-09-05 16:07:05 +00:00Commented Sep 5, 2010 at 16:07
-
I'm testing my program which happens to use the database.Jack Edmonds– Jack Edmonds2010-09-05 16:14:28 +00:00Commented Sep 5, 2010 at 16:14
-
I'm testing a class which is used to access to data in databaseIlya Serbis– Ilya Serbis2015-06-17 22:17:32 +00:00Commented Jun 17, 2015 at 22:17
5 Answers
you can config your hibernate configuration file to force database to recreate your tables and schema every time.
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create-drop</property>
hibernate.hbm2ddl.auto Automatically validates or exports schema DDL to the database when the SessionFactory is created. With create-drop, the database schema will be dropped when the SessionFactory is closed explicitly.
e.g. validate | update | create | create-drop
if you don't like to have this config in your real hibernate config, you can create one hibernate config for unit testing purpose.
2 Comments
If you are using Spring, then you can use the @Transactional attribute on your unit test, and by default at the end of every unit test all persisted data will be automatically rolled back so you dont need to worry about dropping the tables every time.
I haa walked throug an example here http://automateddeveloper.blogspot.com/2011/05/hibernate-spring-testing-dao-layer-with.html
Comments
From testing perspective, the best practice is to clear data after every single test. If you use create-drop, it will also drop the table schema. This causes an overhead of recreating the schema everytime.
Since you are using hsql, which provides a direct mechanism to truncate, it would be the best option in this case.
@After
public void clearDataFromDatabase() {
//Start transaction, based on your transaction manager
dao.executeNativeQuery("TRUNCATE SCHEMA PUBLIC AND COMMIT");
//Commit transaction
}
Comments
Be careful with wiping the world and starting over fresh each time. Soon, you will likely want to start with a "default" set of test data loaded in your system. Thus, what you really want is to revert to that base state before each test is ran. In this case, you want a Transaction which rollsback before each test run.
To accomplish this, you should 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() {
...
}