Unit Testing Data Access Code

There are a lot of challanges to write unit-tests for database facing code. It typically requires a lot of setup code, a lot of effort to maintain, and hard to make it repeatable. It has seemed to be a universal excuse for a lot of teams to drop TDD practice.

So I gather here all various approaches that I am aware of when dealing with database unit-testing. In the next several posts, I will cover each of the implementations in detail, but let’s just have a quick overview on all the options. More than anything else, it’s just a matter of taste really, rather than situational. Hopefully after the next several posts you can make out the good and the bad of each approach.

  1. In-memory database using Sqlite
  2. Transaction rollback
  3. Restorable file-based DB
  4. Preset state with NDBUnit
  5. Fake DB provider with Linq

Throughout the major part of these posts, I will assume the use of nHibernate. Why? Simply because we need somewhere to work on. These approaches are however equally applicable to virtually any ORM or data-access framework.

PS: It is perfectly valid to argue that these are all integration tests, rather than unit-tests. But I digress.

Advertisements

3 thoughts on “Unit Testing Data Access Code

  1. Prior to adopting CoolStorage.NET we always implemented the repository pattern in some form. My team and I were never really happy with this pattern however as noone wanted to invest the time to write our own custom query system (we’re a .NET 2.0 shop still so LINQ isn’t a real option yet).

    Finally, after moving to CoolStorage.NET for ORM, we were left with the ActiveRecord pattern… Now what? Write repositories that wrap around ActiveRecord objects that are mapped to non-active record objects?!

    There are lots of options and patterns one could use, but ultimately we decided that the goal was to be able to test our domain objects (including the mappings) and not write even more code. As such we went with the In-Memory DB solution. After 4 weeks with this solution I must say it works really well. In fact, the tests end up revealing far more about our implementations and its “rightness” then I thought it would.

    Just a word of note: we used VistaDB for our in-memory tests…

    In the end we must leave aside semantics and just make things work. I don’t really care if the test is “Integration” or “Unit”, only that it runs pretty fast and actually tests what I need it to test.

    I look forward to reading your coverage of these methods.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s