Wednesday, September 02, 2009

Unit testing database code via mocking/isolation and the Repository pattern - “Eliminate Database Dependencies in Test-Driven Development”

Visual Studio Magazine - Eliminate Database Dependencies in Test-Driven Development

image

Many developers are tasked with writing unit tests as test-first design and development becomes commonplace, even on teams that aren't strictly practicing Agile methodologies. Test-driven development (TDD) can produce cleaner code by requiring project teams to first write unit tests that fail, then program just enough code for a needed function, retest, refactor and repeat the cycle. If you haven't written code using TDD, starting from a failing test sounds awkward. But it's this extra bit of thought about what you want to achieve that gives you a clearer understanding of what you need to accomplish.

If you're writing an n-tier application using Visual Studio and you're using TDD, it's not uncommon that your unit tests for business-tier functionality read and write to a database. In order for these tests to run, you need a running database with the most up-to-date schema along with any supporting data.

In this article, I'll show you how to leverage the Repository pattern to eliminate the dependency on SQL Server from your unit tests and, in the process, improve your application's testability. The unit-testing features that I discuss in this article are all available in Visual Studio 2008 Professional Edition and in all Visual Studio 2008 Team Editions. The sample application is written in Visual Studio 2008 Team Suite and requires an instance of SQL Server or SQL Express. See the readme.txt for information about how to set up the database and where to find the connection string.

…”

This is one of the challenges in our code base, it’s very old (sigh.. upgraded from VB6… sigh… but it works at least…  ;) and was not designed for isolation nor unit testing. Not that we don’t test! We have thousands of tests in our CI process, but those are really “integration” tests and not “unit” tests. While I’m nowhere near a test zealot, I would really like to be able to execute some DAL testing without having to jump through database setup/rollback/etc hoops.

That’s why this article caught my eye. Added to my stack of stuff to read and grok… ;)

(via Benjamin Day Consulting, Inc.: The Blog - Article: “Eliminate Database Dependencies in Test-Driven Development”)

No comments: