unitils

I recently moved some code from JDBC Templates to Hibernate, Spring and JPA annotations. While not rocket science still something that is slightly tedious to test…. Also if you mock, you are not entirely sure that everything actually works as expected in a full stack. With a bit of Google-Fu I stumbled upon Unitils.

First off – you need to configure unitils to work against a test-db, put
the unitils.properties file into the classpath of your test source

# Properties for the PropertiesDataSourceFactory
#database.driverClassName=org.hsqldb.jdbcDriver
database.driverClassName=org.postgresql.Driver
#database.url=jdbc:hsqldb:mem:javabot-test
database.url=jdbc:postgresql:javabot-test
database.userName=username
database.password=password
# This property specifies the underlying DBMS implementation. Supported values are 'oracle', 'db2', 'mysql', 'hsqldb' and 'postgresql'.
# The value of this property defines which vendor specific implementations of DbSupport and ConstraintsDisabler are chosen.
database.dialect=postgresql
# This property specifies the database schema that is used. This schema name is used to qualify all tables when (amongst
# others) clearing / dropping tables / inserting test data.
# NOTE: schema name is case sensitive
database.schemaName=public
updateDataBaseSchema.enabled=true
dbMaintainer.fileScriptSource.scripts.location=src/tests/javabot/dbscripts
dbMaintainer.generateDTD.enabled=TRUE
# DbUnit database DTD file path
dtdGenerator.dtd.filename=src/tests/javabot/dbscripts/test.dtd

Following the Spring-Tutorial I was able to quickly whip up a spring-context.

The magic is in this line :

<bean id=”dataSource” class=”org.unitils.database.UnitilsDataSource” />

So essentially you replace your existing data source, and use the unitils one.

 Which now will let me via these lines
@SpringApplicationContext("test-application-config.xml")
public class BaseServiceTest extends UnitilsTestNG {
    @SpringApplicationContext
    ApplicationContext springApplicationContext;
}
This base class then makes us ready for testing......
 public class SeenDaoTest extends BaseServiceTest { 

    @SpringBeanByType
    private SeenDao seenDao; 

    @Test
    public void addSeen() {
       seenDao.logSeen("nick","channel","message");
       Assert.assertTrue(seenDao.isSeen("nick","channel"));
    }
}

Contained beneath the hood we now have a complete Spring / Hibernate live database test!

Leave a Reply

You must be logged in to post a comment.