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

I'd like to write some unit tests for some code that connects to a database, runs one or more queries, and then processes the results. (Without actually using a database)

Another developer here wrote our own DataSource, Connection, Statement, PreparedStatement, and ResultSet implementation that will return the corresponding objects based on an xml configuration file. (we could use the bogus datasource and just run tests against the result sets it returns).

Are we reinventing the wheel here? Does something like this exist already for unit testing? Are there other / better ways to test jdbc code?


Solution 1:

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.

Solution 2:

You could use DBUnit together with a HSQLDB which can read its initial data from CSV files for example.

Solution 3:

I like to use a combination of:

  • DBUnit
  • HSQLDB
  • Unitils (specifically, the database testing and maintenance modules)

You can get pretty far with just DBUnit and HSQLDB. Unitils provides the last mile of code to manage and reset database state. It also provides a nice way of managing database schema changes and makes it easy to use specific RBDMS (Oracle, DB2, SQL Server, etc). Finally, Unitils provides some nice wrappers around DBUnit which modernizes the API and makes DBUnit much more pleasant to work with.

If you haven't checked out Unitils yet, you definitely should. Unitils is often overlooked and under-appreciated.

Solution 4:

That's why you have derby (now called JavaDB) or sqlite -- they are small, simple databases that you can create, load, test against and destroy relatively quickly and simply.

Solution 5:

I would say that HSQL is the way to go during your unit tests. The point of your test is to test your jdbc code and make sure it works. Adding custom classes or mocking the jdbc calls can easily hide bugs.

I mostly use mysql and when the tests run the driver class and url is changed to org.hsqldb.jdbcDriver and jdbc:hsqldb:mem:test.