Writing Testable JDBC Code

Problem

You want to design your JDBC code so it is testable.

Solution

Modularize your code so that the JDBC connection is created independently of your database logic. This allows you to test your logic using a mock connection, statement, and result set.

Tip

This solution illustrates a generally useful pattern. When you create an object, give it references to the objects it needs to talk to, rather than having it go somewhere and get them. This step gives you the ability to reuse the object in other applications or test it in isolation. The idea is not specific to JDBC.

Discussion

A good unit test exercises a small piece of functionality in isolation from the remainder of the system. You may want to test your JDBC logic without actually creating a real database. Testing without a database is advantageous for numerous reasons:

  • The tests run faster.

  • You don’t have to keep a testing database in sync with your unit tests.

  • You can test all sorts of error conditions without going to the trouble of creating invalid data in your database.

Testing against a real database is very important, but can be done separately from your other tests. You may end up with 25 tests that actually use a real database and another 50 tests that simulate the database using mock objects. Effective testing requires a variety of approaches (and plenty of creativity) to ensure adequate coverage and good test performance.

Let’s start with a class called AccountFactory containing a method that retrieves ...

Get Java Extreme Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.