DBUnit – Need for creating tables

While doing unit testing for my DAO’s with DBunit, I never really realized that I have to explicitly create tables in the in-memory database and having an XML for the test data or even a DTD to validate it is not enough. That was till I planned to use JDBC and not hibernate to implement the DAO’s.
While woking with Hibernate it was always so easy to just turn on the hibernate.hbm2ddl.auto to update as part of hibernate properties and that is it, hibernate takes care of creating the schema from the hbm files or the respective annotations. But with JDBC, we have to explicitly create the tables in the in-memory database otherwise executing the test case will throw NoSuchTableException.
The easiest way to do it, is to execute the following.

SimpleJdbcTestUtils.executeSqlScript(new SimpleJdbcTemplate(getDataSource()),
new ClassPathResource("CreateTables.sql"), true);

Obviously we can use the above if we are using spring framework.

Leave a Reply