Testing your JDBC data access layer with DBUnit and H2
September 18th, 2007 jasonkIn most server-side applications there will be a requirement to persist your data to some storage layer. Spring provides a neat abstraction in the form of the JdbcTemplate to achieve this, and in combination with a Spring-injected DataSource you can easily switch your data source between testing and production databases. Unfortunately the recommended and well-publicised test strategies for *integration* testing of your applications involving Apache Derby, HSQL (HSQLDB), and MySQL don’t enable rapid-fire *unit* testing of your data access code, since they require a real database to be at some known location on your disk or on a server (or in the case of HSQL don’t completely support all of the JDBC-3.0 spec).
Today, I’ll take you through combining some free components that enable you to run unit tests on your JDBC data access layer in a completely in-memory fashion, which allows you to more easily run regular complete and predictable tests of your data access layer and get consistent results. In fact, this solution isn’t limited to just Spring applications; any JDBC code can be tested like this!