Monday, April 29, 2013

Unit Tests with IN-Memory Database


HSQLDB can be to build framework as a in memory database for unit testing
What to be done
Add following to properties file and this should be loaded to Spring config

# Database properties for library services

datasource.driver.class.name = org.hsqldb.jdbcDriver
datasource.url = jdbc:hsqldb:mem:unittest
datasource.user.name = sa
datasource.user.password = test
hdb.dialect = org.hibernate.dialect.HSQLDialect
hdb.show_sql = true
hdb.hbm2ddl.auto = update

Add following line to Spring configuration

<jdbc:embedded-database id="embedded" type="HSQL" />
<jdbc:initialize-database data-source="dataSource">
    <jdbc:script location="classpath:schema.sql" />
    <jdbc:script location="classpath:data.sql" />
</jdbc:initialize-database>

Add necessary SQL files

schema.sql - SQL to create the tables and its relationships data.sql - Basic data 

Write a JUnit Test class pointing to new Spring config

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:dispatcher-servlet.xml" })
public class BoundryTestClass {
..

}