Thursday, April 28, 2005

Unit Testing Database Code

Unit testing has become second hand to many developers lately. I strive to keep my jUnit coverage as high as possible, and my unit tests as relevant as possible. But over the years, I've consistently run into one nagging problem. How do you unit test code that interacts with a database?

The answer, on the surface, is a simple one: write a unit test that calls a method and check its result. But, that means whomever builds your project needs to have access to the appropriate database, either that, or build without testing. So the alternative is to "mock" up the database connection and "pretend" to make calls to the database. I've had good success using MockObjects to do just that, but ran aground again when I found out that MockObjects doesn't support callable statements very well. That's okay though, because even if it did, your bypassing a large portion of logic that, in this case, is running as a stored procedure. What good it testing a method that does nothing but shove off responsibility to a database that the build environment may not have access to?

Maybe this falls more into the integration testing realm, where it can be assumed that you have a connected database. That does nothing for the large red line in my coverage report though :(