JUnit for database code


I've been trying to implement unit testing and currently have some code that does the following:

  1. query external database, loading into a feed table
  2. query a view, which is a delta of my feed and data tables, updating data table to match feed table

my unit testing strategy is this:

I have a testing database that I am free to manipulate.

  1. in setUP(), load some data into my testing db
  2. run my code, using my testing db as the source
  3. inspect the data table, checking for counts and the existence/non existence of certain records
  4. clear testing db, loading in a different set of data
  5. run code again
  6. inspect data table again

Obviously I have the data sets that I load into the source db set up such that I know certain records should be added,deleted,updated, etc.

It seems like this is a bit cumbersome and there should be an easier way? any suggestions?


If you are using Maven, one option is to use the sql-maven-plugin. It allows you to run database initialization/population scripts during the maven build cycle.

Apart from the already suggested DBUnit, you may want to look into Unitils. It uses DBUnit, but provides more than that (quoting from the site):

  • Automatic maintenance of databases, with support for incremental, repeatable and post processing scripts
  • Automatically disable constraints and set sequences to a minimum value
  • Support for Oracle, Hsqldb, MySql, DB2, Postgresql, MsSql and Derby
  • Simplify test database connection setup
  • Simple insertion of test data with DBUnit * Run tests in a transaction
  • JPA entity manager creation and injection for hibernate, toplink and * Hibernate SessionFactory creation and session
  • Automatically test the mapping of JPA entities / hibernate mapped objects with the database

I use DbUnit, but also I work very hard to not to have to test against the DB. Tests that go against the database should only exist for the purpose of testing the database interface. So I have Mock Db Connections that I can set the data for use in all the rest of my tests.

By : Aaron

This video can help you solving your question :)
By: admin