Spring Dao/JDBC tip - a great way to test your Spring DAO code

The Spring Framework gives you a great way to test your Spring JDBC (Spring DAO) code. Just use a special Spring JDBC class with a very long name, and you can test your Spring JDBC code against a real database.

Some people don't like this approach, but I think it's invaluable for (a) testing your SQL syntax when you first create it, and (b) making sure your SQL syntax is still valid after database changes occur.

Spring Dao/JDBC test code

Here's some example Java test code where I extend the Spring JDBC AbstractTransactionalDataSourceSpringContextTests class to run some simple database tests using JUnit.

In my Spring DAO test, I load the Spring application context file (applicationContext.xml), get a reference to my Spring DAO object (ftpFileMoverDao), then pass that DAO object into another object, and then run some tests that hit the database behind the scenes.

I tried to keep this simple, but I wanted to have an example where I showed how to use the Spring JDBC AbstractTransactionalDataSourceSpringContextTests class, and also load the Spring application context file.

As mentioned, I personally like having regression tests that make sure that I won't have a problem when the database schema changes, and I think this Spring JDBC testing approach of having tests like this that run within a transactional context, and then are rolled back for you automatically, is pretty darn clever.

Here's my Spring DAO test class:

package com.devdaily.foo.controller;

import java.util.Calendar;
import java.util.Date;

import org.junit.Assert;
import org.junit.Test;
import org.springframework.test.AbstractTransactionalDataSourceSpringContextTests;

import com.devdaily.foo.dao.FTPFileMoverDao;

public class StorEventHandlerTests 
extends AbstractTransactionalDataSourceSpringContextTests
{

  FTPFileMoverDao ftpFileMoverDao;

  @Override
  protected String[] getConfigLocations()
  {
    return new String[] { "applicationContext.xml" };
  }
 
  /**
   * Test the valid file extensions we keep in the database.
   */
  @Test
  public void testValidFileExtensions()
  {
    // mimic how the application normally gets a handle on our dao object
    ftpFileMoverDao = (FTPFileMoverDao) applicationContext.getBean("ftpFileMoverDao");

    // create the storEventHandler, then give it the dao
    StorEventHandler storEventHandler = new StorEventHandler(null);
    storEventHandler.setFTPFileMoverDao(ftpFileMoverDao);

    // run the tests
    Assert.assertTrue(storEventHandler.fileExtensionIsValid("JPG"));
    Assert.assertTrue(storEventHandler.fileExtensionIsValid("JPEG"));
    Assert.assertTrue(storEventHandler.fileExtensionIsValid("PNG"));
  }

}

I hope you can use this Java/Spring/JDBC/Dao test code in your own applications. I really do think this is a terrific feature of the Spring JDBC Framework.