In his inaugural JavaRanch Journal article, Lasse Koskela shares some good advice on unit testing database code and provides a primer on using mock objects to help. Any comments on the article? [ December 30, 2003: Message edited by: Lasse Koskela ]
The article is a good example of how to take something with integration complexities and factor our the integration point in order to enable unit testing. On the other hand, you have to pay attention to how much bang you got out of the tests themselves. Testing against a database is really an integration test, not a unit test. Integration tests that factor out the integration point tend to result in unit tests that don't do much. You can see that in each of the tests examples until you get to the last one (the 'sandbox' approach as he calls it), using dbUnit. It has some meat to it, but that is because it has shifted back into the integration test space again. Factoring out integration points is more valuable for constructing unit tests of the things that call DAOs, not as much for testing DAOs themselves. If your DAO has enough logic in it to warrant a true unit test, then you've probably got a cohesion problem (stuff in the DAO class that probably doesn't belong there). The only way I know of to get around the integration-tests-without-integration-points-aren't-valuable-unit-tests problem is to switch from mock objects to simulators. For example, you could create a database connection simulator that would parse the SQL in the statements to let you know if it was syntactically correct and had the right number of bind parameters. Mock objects (deliberately) don't have that level of smarts. [ December 30, 2003: Message edited by: Reid M. Pinchback ]
Reid's point about the need of unit testing database code at all is valid. I had a sentence or two about exactly that dilemma, but had apparently edited it away. Regardless of this, I have found it valuable to have tests to keep those PreparedStatement variables in check. Thanks for the feedback!