Getting started with Unit Testing of JDBC based DAOs with the Spring Framework (introducing DBUnit)

1

For one of our Java projects, I wanted to help a colleague getting
started with unit testing. Due to high time pressure, there was a real
risk that – and we know it should not happen that way – unit tests
might be pushed backwards in time. The project is using the Spring
Framework in different places: Spring Core (IoC Container), Spring
JDBC/Spring DAO, Spring MVC in the WebTier and Spring with Acegi for
the security of the application. The unit testing initially has to deal
with the DAOs. These Data Access Objects are developed using Spring
JDBC though we consider – if we have another resource available –
moving to Spring Hibernate at some later point in time. To allow a
smooth transition, all DAO implementation classes are hidden behind DAO
interfaces; the Business Service that presents data services to the web
application is itself injected with the DAOs by the Spring Container.
We can replace the current JDBC based DAO Implementation Classes later
on with Spring Hibernate based implementations that implement the same
interface, leaving the Business Service none the wiser about this
switch.

So how to unit test these Spring JDBC driven DAO implementations?....

I have set up a small demonstration. It consists of:

  • a single database table, ALS_PUBLISHERS
  • a
    class Publisher – the Object representation mapped to the table- and
    its companion DAO interface PublisherDao as well a an implementation
    PublisherDaoJdbcImpl
  • a class TestPublisherDao that extends from JUnit TestCase and performs the unit tests for the PublisherDao under scrutiny
  • a
    Spring Bean Configuration File that sets up a JDBC DataSource, the Dao
    Implementation that we will test and injects both in the
    TestPublisherDao class

I make use of Eclipse 3.1 for the demonstration, although any IDE or even no IDE would have worked.

In configuring the project, I add the following jars to the Build Path:

  • spring-1.2.5.jar (the jar containing most of the Spring Framework)
  • commons-logging-1.0.4.jar (used by Spring)
  • spring-mock-1.2.1.jar
    (this library contains the class
    AbstractDependencyInjectionSpringContextTests that extends JUnit’s
    TestCase)
  • junit-3.8.1.jar (in order to set up and run Unit Tests)

The latter two libraries are required for the unit tests, the first two are part of the application.

The ALS_PUBLISHERS table is defined like this:

CREATE TABLE &quot;ALS_PUBLISHERS&quot;<br />(<br />&quot;ID&quot; NUMBER (10,0) NOT NULL,<br />&quot;WEBSITE&quot; VARCHAR2 (50),<br />&quot;NAME&quot; VARCHAR2 (50),<br />&quot;COUNTRY&quot; VARCHAR2 (2),<br />&quot;LOCATION_IN_COUNTRY&quot; VARCHAR2 (50),<br />&quot;LOGO&quot; BLOB,<br />  CONSTRAINT PBR_PK<br />  PRIMARY KEY ( ID ) <br />)<br />;

The Publisher POJO that reflects this table looks like:

package nl.amis.als.domain;<br /><br />public class Publisher {<br /><br />	private Long id;<br />	private String name;<br />	private String website;<br /><br />	public Long getId() {<br />		return id;<br />	}<br />	public void setId(Long id) {<br />		this.id = id;<br />	}<br />	<br />	public String getName() {<br />		return name;<br />	}<br />	public void setName(String name) {<br />		this.name = name;<br />	}<br />	<br />	public String getWebsite() {<br />		return website;<br />	}<br />	public void setWebsite(String website) {<br />		this.website = website;<br />	}<br />	<br />}<br />&nbsp;

The Data Access Object interface that is defined for the Publisher domain class has been defined here:

package nl.amis.als.dao;<br /><br />import java.util.List;<br /><br />import nl.amis.als.domain.Publisher;<br /><br />public interface PublisherDao {<br /><br />    public List selectAllPublishers();<br />    <br />    public Publisher findPublisher(Long id);<br /><br />    public void insertPublisher(Publisher pub);<br />    <br />    public void deletePublisher(Publisher pub);<br />    public void deletePublisher(Long id);<br />}<br />&nbsp;

Granted,
this interface is relatively poor. We could define many more query
methods as well as an update operation. For this introduction into DAO
Unit testing with the Spring framework it does not really matter.

We
could have implemented the DAO interface in several ways, using
frameworks such as iBatis, TopLink or HIbernate or using Spring JDBC.
In this case, we have opted for the latter: plain JDBC or rather JDBC
using the Spring Templates that take care of much plumbing code like
TCTCF (try-catch-try-catch-finally). The class PublisherDaoJdbcImpl
extends the Spring JdbcDaoSupport class and implements the PublisherDao
interface. We see the interface methods implemented with relatively few
lines of code: most of the JDBC plumbing is found in the Spring
JdbcDaoSupport class.

package nl.amis.als.dao.jdbc;<br /><br />import java.util.ArrayList;<br />import java.util.Iterator;<br />import java.util.List;<br />import java.util.Map;<br /><br />import nl.amis.als.dao.PublisherDao;<br />import nl.amis.als.domain.Publisher;<br />import java.sql.ResultSet;<br />import java.sql.SQLException;<br /><br />import org.springframework.jdbc.core.JdbcTemplate;<br />import org.springframework.jdbc.core.RowMapper;<br />import org.springframework.jdbc.core.RowMapperResultReader;<br />import org.springframework.jdbc.core.support.JdbcDaoSupport;<br /><br />public class PublisherDaoJdbcImpl extends JdbcDaoSupport implements<br />		PublisherDao {<br /><br />	 public List selectAllPublishers() {<br />	        JdbcTemplate jt = getJdbcTemplate();<br />	        return jt.query ( &quot;select id, name, website from als_publishers&quot;<br />	                        , new RowMapperResultReader(new PublisherRowMapper())<br />	                        );<br />	    }//getAllPublishers<br />	        <br />	    // this inner class is invoked for each Row om the ResultSet. It implements<br />	    // the Spring RowMapper interface, that is used to convert ResultSet records<br />	    // to Domain Objects. RowMappers are used when the results are not simple<br />	    class PublisherRowMapper implements RowMapper {<br />	      public Object mapRow(ResultSet rs, int index) throws SQLException {<br />	        Publisher pub = new Publisher();<br />	        pub.setId(new Long(rs.getLong(1)));<br />	        pub.setName(rs.getString(2));<br />	        pub.setWebsite(rs.getString(3));<br />	        return pub;<br />	      }      <br />	    }//class PublisherRowMapper<br />	<br /><br />	public Publisher findPublisher(Long id) {<br />		JdbcTemplate jt = new JdbcTemplate(super.getDataSource());<br />		Publisher pub = new Publisher();<br />		Object[] parameters = new Object[] { id };<br />		List l = jt.queryForList(<br />				&quot;select id, name, website from als_publishers where id = ?&quot;,<br />				parameters);<br /><br />		Iterator iter = l.iterator();<br />		while (iter.hasNext()) {<br />			Map m = (Map) iter.next();<br />			pub.setId(new Long(m.get(&quot;ID&quot;).toString()));<br />			pub.setName((String) m.get(&quot;NAME&quot;));<br />			pub.setWebsite((String) m.get(&quot;WEBSITE&quot;));<br />		}<br />		return pub;<br />	}<br /><br />	public void insertPublisher(Publisher pub) {<br />		JdbcTemplate jt = new JdbcTemplate(super.getDataSource());<br />		Object[] parameters = new Object[] { pub.getId(), pub.getName(),<br />				pub.getWebsite() };<br />		int rows = jt.update(&quot;insert into als_publishers (id, name, website)&quot;<br />				+ &quot; values ( ?, ?, ?)&quot;, parameters);<br />	}<br />	public void deletePublisher(Publisher pub) {<br />		deletePublisher(pub.getId());<br />	}<br /><br />	public void deletePublisher(Long id) {<br />		JdbcTemplate jt = new JdbcTemplate(super.getDataSource());<br />		Object[] parameters = new Object[] { id};<br />		int rows = jt.update(&quot;delete from als_publishers where id = ?&quot;, parameters);<br />	}<br /><br />} <br />

Notice
that while we cannot see it in this class, it still requires a
DataSource to be injected. The setDataSource() method is in the super
class JdbcDaoSupport.

With the DAO Interface in hand, we can
already start writing the Unit Test for the DAO. This test class
extends from the class AbstractDependencyInjectionSpringContextTests
from the Spring Mock library. This class extends JUnit TestCase. It
implements the SetUp() method – as a final method. However, it provides
a hook into this SetUp() through the onSetUp() method that we can
override in our own class; this is another example of the Template
Pattern. The AbstractDependencyInjectionSpringContextTests class
contains an abstract method protected String[] getConfigLocations()
that we must implement. We have this method return a String array with
the names of all Bean Configuration files that should be for injecting
dependencies. The second action performed by this class is so-called
auto-wiring: when our TestCase, extending from
AbstractDependencyInjectionSpringContextTests, is run as JUnit Test,
the class will be injected with dependencies- all setter methods in the
test class that correspond with the bean names in the specified Bean
Configuraton files are injected with the beans as produced by the IoC
Container.

We make use of this feature to have the Publisher DAO Implementation injected.

Our
test class is very simple, again I am mainly trying to demonstrate the
principles. It tests the selectAllPublishers() implementation, assuming
that it must return at least one record. It also attempts to test the
insertPublisher(), findPublisher() and deletePublisher() methods.

package nl.amis.als.dao.test;<br /><br />import java.io.FileInputStream;<br />import java.sql.Connection;<br />import java.sql.DriverManager;<br />import java.util.List;<br /><br />import javax.sql.DataSource;<br /><br />import nl.amis.als.dao.PublisherDao;<br />import nl.amis.als.domain.Publisher;<br /><br />import org.springframework.test.AbstractDependencyInjectionSpringContextTests;<br /><br />public class PublisherDaoTest extends AbstractDependencyInjectionSpringContextTests {<br /><br />	<br />	public void testFindAllPublishers() {<br />          List l = publisherDao.selectAllPublishers();<br />          // there should be more than one Publisher returned<br />          assertTrue(l.size()&gt;0);<br />	}<br /><br />	public void testCreateAndFindPublisher() {<br />        Publisher pub = new Publisher();<br />        pub.setId(new Long(133));<br />        pub.setName(&quot;My New Publisher&quot;);<br />        pub.setWebsite(&quot;my.web.com&quot;);<br />        publisherDao.insertPublisher(pub);<br />        Publisher pub2 = publisherDao.findPublisher(new Long(133));<br />        assertEquals(pub2.getName(),pub.getName());<br />	publisherDao.deletePublisher(pub2);<br />        Publisher pub3 = publisherDao.findPublisher(pub2.getId());<br />        assertNull(pub3.getId() );<br />		<br />	}<br /><br />	<br />    // specify the BeanConfigurationFiles to use for auto-wiring the properties of this class<br />	protected String[] getConfigLocations() {<br />	        return new String[]{&quot;AlsTestContext.xml&quot;};<br />	    }<br /><br />    // this private property is injected through the setter from the BeanConfigurationFile<br />	// specified in getConfigLocations()<br />	private PublisherDao publisherDao;<br />	public PublisherDao getPublisherDao() {<br />		return publisherDao;<br />	}<br /><br />	public void setPublisherDao(PublisherDao publisherDao) {<br />		this.publisherDao = publisherDao;<br />	}<br /><br />}<br /><br />

The one thing still lacking for running our Unit Test is the Bean Configuration file. Here it is:

&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br />&lt;!DOCTYPE beans PUBLIC &quot;-//SPRING//DTD BEAN//EN&quot; &quot;http://www.springframework.org/dtd/spring-beans.dtd&quot;&gt;<br />&lt;!--  - Application context definition for &quot;springapp&quot; DispatcherServlet.  --&gt;<br />&lt;beans&gt;<br />	&lt;!-- datasource configuration:<br />		View context.xml and server.xml for more datasource configuration --&gt;<br />	&lt;bean id=&quot;dataSourceDBDirect&quot;<br />		class=&quot;org.springframework.jdbc.datasource.DriverManagerDataSource&quot;<br />		destroy-method=&quot;close&quot;&gt;<br />		&lt;property name=&quot;driverClassName&quot;<br />			value=&quot;oracle.jdbc.driver.OracleDriver&quot; /&gt;<br />		&lt;property name=&quot;url&quot;<br />			value=&quot;jdbc:oracle:thin:@localhost:1521:orcl&quot; /&gt;<br />		&lt;property name=&quot;username&quot; value=&quot;als&quot; /&gt;<br />		&lt;property name=&quot;password&quot; value=&quot;als&quot; /&gt;<br />	&lt;/bean&gt;<br /><br />	&lt;!--  resource bundle location <br />	--&gt;<br />	&lt;bean id=&quot;messageSource&quot;<br />		class=&quot;org.springframework.context.support.ResourceBundleMessageSource&quot;<br />		abstract=&quot;false&quot; singleton=&quot;true&quot; lazy-init=&quot;default&quot;<br />		autowire=&quot;default&quot; dependency-check=&quot;default&quot;&gt;<br />		&lt;property name=&quot;basename&quot;&gt;<br />			&lt;value&gt;messages&lt;/value&gt;<br />		&lt;/property&gt;<br />	&lt;/bean&gt;<br /><br />	&lt;!-- ********** JDBC DAOs ********** --&gt;<br /><br />	&lt;bean id=&quot;publisherDao&quot;<br />		class=&quot;nl.amis.als.dao.jdbc.PublisherDaoJdbcImpl&quot;&gt;<br />		&lt;property name=&quot;dataSource&quot;&gt;<br />			&lt;ref local=&quot;dataSourceDBDirect&quot; /&gt;<br />		&lt;/property&gt;<br />	&lt;/bean&gt;<br /><br />&lt;/beans&gt;<br />&nbsp;

Note that normally our application would be getting a DataSource
from the Web/Servlet Container in which our application runs. However,
since we test outside the container, we inject our own DataSource,
produced by the Spring class
org.springframework.jdbc.datasource.DriverManagerDataSource. Note how
the setPublisherDao method in our test class corresponds with the
publisherDao bean set up in this configuration file.

Controlling the Test Data Set using DBUnit 

In
order to be able to write tests based on the actual data set in the
table, we need to control the data in the table. For this, we will use DBUnit.
DBUnit can be used to construct tests on the contents of database
tables. However, its importance to us right now lies in DBUnit’s
functionality for controlling the data in the tables: " DbUnit is a JUnit extension (also usable with Ant) targeted for database-driven projects that,
among other things, puts your database into a known state between test runs. This is an excellent
way to avoid the myriad of problems that can occur when one test case corrupts the database and
causes subsequent tests to fail or exacerbate the damage.
"

In
order to set up DBUnit in my project, I need to download dbunit-2.1.jar
as well well commons-io-1.0.jar. I add them both to the Build Path as
external archive.

DBUnit can load the test data set into the
target tables from for example an XML File. Later we will see how this
data is loaded by DBUnit in the setup stage of our Unit Test. We will
first see how we can use DBUnit to create the XML file from extracting
data from the table. The class

package nl.amis.als.dao.test;<br /><br />import java.io.FileOutputStream;<br />import java.sql.Connection;<br />import java.sql.DriverManager;<br /><br />import org.dbunit.database.DatabaseConnection;<br />import org.dbunit.database.IDatabaseConnection;<br />import org.dbunit.dataset.DefaultDataSet;<br />import org.dbunit.dataset.ITable;<br />import org.dbunit.dataset.filter.DefaultColumnFilter;<br />import org.dbunit.dataset.xml.FlatXmlDataSet;<br /><br />public class ExtractAlsTestData {<br /><br />	public static void main(String[] args) throws Exception {<br />		// database connection<br />		Class driverClass = Class.forName(&quot;oracle.jdbc.driver.OracleDriver&quot;);<br />		Connection jdbcConnection = DriverManager.getConnection(<br />				&quot;jdbc:oracle:thin:@localhost:1521:orcl&quot;, &quot;als&quot;, &quot;als&quot;);<br />		IDatabaseConnection connection = new DatabaseConnection(jdbcConnection);<br /><br />		// add the table ALS_PUBLISHERS for data extraction<br />		ITable tbl = connection.createQueryTable(&quot;als_publishers&quot;,<br />				&quot;SELECT * FROM als_publishers &quot;);<br />		// exclude column LOGO from the data extraction<br />		ITable filteredTable = DefaultColumnFilter.excludedColumnsTable(tbl,<br />				new String[] { &quot;LOGO&quot; });<br />		// create a dataset with table ALS_PUBLISHERS<br />		DefaultDataSet partialDataSet = new DefaultDataSet();<br />		partialDataSet.addTable(filteredTable);<br />		// have DBUnit write the table data to an XML file<br />		FlatXmlDataSet.write(partialDataSet, new FileOutputStream(<br />				&quot;als-publishers-dataset.xml&quot;));<br />	}<br />}<br /><br />

This
class will generate the file als-publishers-dataset.xml. We have taken
care not to include the LOGO column of type BLOB. Not that DBUnit
cannot handle it, it just sort of messes up our xml file and we will
not do any testing on the binary data in this column. It took some time
to find out how to use the Column Filters (see DBUnit – how to exclude some columns at runtime). Note that it would be easy to add additional tables from the ALS Schema to this extraction class. Also note that article DBUnit Made Easy
explains a way to write a Spring based utility class that can easily be
configured and run for extracting data. The resulting file –
als-publishers-dataset.xml – looks like this:

&lt;?xml version='1.0' encoding='UTF-8'?&gt;<br />&lt;dataset&gt;<br />  &lt;als_publishers ID=&quot;16&quot; WEBSITE=&quot;www.evengreaterbooks-inc.com&quot; NAME=&quot;My Publishing House&quot;/&gt;<br />  &lt;als_publishers ID=&quot;2&quot; WEBSITE=&quot;www.wrox.com&quot; NAME=&quot;Wrox (label of Wiley Publishing)&quot; LOCATION_IN_COUNTRY=&quot;Indianapolis (IN)&quot;/&gt;<br />  &lt;als_publishers ID=&quot;3&quot; WEBSITE=&quot;www.wiley.com2&quot; NAME=&quot;Wiley and Sons and grandsons&quot; LOCATION_IN_COUNTRY=&quot;New York (NY)&quot;/&gt;<br />  &lt;als_publishers ID=&quot;4&quot; WEBSITE=&quot;http://www.manning.com&quot; NAME=&quot;Manning Publications Co.&quot; COUNTRY=&quot;us&quot;/&gt;<br />  &lt;als_publishers ID=&quot;5&quot; WEBSITE=&quot;http://java.sun.com&quot; NAME=&quot;SUN Microsystems&quot;/&gt;<br />  &lt;als_publishers ID=&quot;6&quot; WEBSITE=&quot;http://books.mcgraw-hill.com&quot; NAME=&quot;McGrawHill&quot; COUNTRY=&quot;nl&quot;/&gt;<br />  &lt;als_publishers ID=&quot;1&quot; WEBSITE=&quot;www.oreilly.com&quot; NAME=&quot;O&amp;apos;Reilly&quot; COUNTRY=&quot;uk&quot; LOCATION_IN_COUNTRY=&quot;Sebastopol, CA&quot;/&gt;<br />  &lt;als_publishers ID=&quot;15&quot; WEBSITE=&quot;www.greatbooks-inc.com&quot; NAME=&quot;My Publishing House&quot;/&gt;<br />&lt;/dataset&gt;<br />&nbsp;

Now
we are going to benefit from this dataset in our Test Class. We do so
by overriding the onSetUp() method that is defined in the
AbstractDependencyInjectionSpringContextTests superclass.

 

import org.dbunit.database.DatabaseDataSourceConnection;<br />import org.dbunit.database.IDatabaseConnection;<br />import org.dbunit.dataset.IDataSet;<br />import org.dbunit.dataset.xml.FlatXmlDataSet;<br />import org.dbunit.operation.DatabaseOperation;<br /><br />	 protected void onSetUp() throws Exception {<br />		super.onSetUp();<br />		// we will use DBUnit to prepare the database with a proper dataset<br /><br />		// initialize your database connection here<br />		IDatabaseConnection connection = new DatabaseDataSourceConnection(<br />				dataSourceDBDirect, &quot;ALS&quot;);<br />		// initialize your dataset here, from the file containing the test<br />		// dataset<br />		IDataSet dataSet = new FlatXmlDataSet(new FileInputStream(<br />				&quot;als-publishers-dataset.xml&quot;));<br /><br />		try {<br />			DatabaseOperation.CLEAN_INSERT.execute(connection, dataSet);<br />		} finally {<br />			connection.close();<br />		}<br />	}<br />&nbsp;

The
CLEAN_INSERT operation will first remove all data from the target
table(s) and then load the data from the specified dataset. This
dataset is created from the als-publishers-dataset.xml. 

We also
need to inject the DataSource into the TestClass as DBUnit needs the
DataSource to load the data from the XML file into the database:

    private DataSource dataSourceDBDirect;<br />    private PublisherDao publisherDao;<br />    <br />    public void setDataSourceDBDirect(DataSource dataSourceDBDirect) {<br />    	this.dataSourceDBDirect = dataSourceDBDirect;<br />    }   <br />	   <br />	public PublisherDao getPublisherDao() {<br />		return publisherDao;<br />	}<br /><br />	public void setPublisherDao(PublisherDao publisherDao) {<br />		this.publisherDao = publisherDao;<br />	}<br /><br />

The dataSourceDBDirect bean is already set up because the DataSource needs to be injected in the DAO Implementation.

At
this point we can start writing unit tests that make assumptions on the
data in the ALS_PUBLISHERS table – as we know how the data has been set
up. For example:

	public void testFindPublisher() {<br />        Publisher pub2 = publisherDao.findPublisher(new Long(6));<br />        assertEquals(pub2.getName(),&quot;McGrawHill&quot;);<br />        assertEquals(pub2.getWebsite(),&quot;http://books.mcgraw-hill.com&quot;);<br />		<br />	}<br />

Resources 

Introducing Spring JDBC – frequently the best introduction of Spring in an organization - AMIS Technology Weblog (September 2005) 

DBUnit homepag

Effective Unit Testing with DbUnit  by Andrew Glover (january 2004) – ONJava.com

DBUnit – how to exclude some columns at runtime

DBUnit Made Easy by Bill Siggelkow Oct. 13, 2005, O’Reilly Network Weblogs

Testing with the Spring Framework – Chapter 23 of the reference documentation

Control your test-environment with DbUnit and Anthill Philippe Girolami 13 Apr 2004, IBM Developer Works

 

Share.

About Author

Lucas Jellema, active in IT (and with Oracle) since 1994. Oracle ACE Director for Fusion Middleware. Consultant, trainer and instructor on diverse areas including Oracle Database (SQL & PLSQL), Service Oriented Architecture, BPM, ADF, Java in various shapes and forms and many other things. Author of the Oracle Press book: Oracle SOA Suite 11g Handbook. Frequent presenter on conferences such as JavaOne, Oracle OpenWorld, ODTUG Kaleidoscope, Devoxx and OBUG. Presenter for Oracle University Celebrity specials.

1 Comment