How do I unit test jdbc code in java? [closed]

You have several options:

  • Mock the database with a Mock library, e.g. JMock. The huge drawback of this that your queries and the data will most likely be not tested at all.
  • Use a light weight database for the tests, such as HSQLDB. If your queries are simple, this is probably the easiest way to go.
  • Dedicate a database for the tests. DBUnit is a good option, or if you are using Maven, you can also use the sql-maven-plugin to set up and tear down the database properly (be careful of dependencies between tests). I recommend this option as it will give you the biggest confidence that the queries work properly with your db vendor.

Sometimes it is necessary and useful to make these tests configurable so that these tests are only executed if the database is available. This can be done with e.g. build properties.

Leave a Comment