TransactionScope for unit testing complex database access code.

Since .NET 2.0 came out, the TransactionScope class has provided an excellent way to manage complex transactions in the simplest way possible: using the scoping rules of the language itself. The basic method for using a TransactionScope couldn't be easier:

using (TransactionScope scope = new TransactionScope())
{
    ... your transactional code here ...
    scope.Complete();
}

An overview of TransactionScope can be found on MSDN.

The idea here is that when you fall out of the scope of the using block the transaction will COMMIT or ROLLBACK. If you call scope.Complete(), the transaction will commit. If you fail to make that call then leaving the scope of the using block will rollback all the work done.

What makes this so amazing is that anything that implements the System.Transaction infrastructure will respect these rules, so you are not just able to work with database providers (which are the most common implementer of System.Transaction) but MSMQ (Micrsoft Message Queueing) and other enterprise components.

There is a trick that is so blindingly obvious that it eludes some programmers for years: the ability to use TransactionScope to test database access code.

The primary problem with testing database logic is that you need to reset the database back to its original condition before you can test again, yet the databasic logic that really needs testing is very complex and includes things such as triggers, constraints and other database level resources that are difficult to mock out.

Enter the TransactionScope: simply wrap your hair raising database logic within it and you gain the ability to make changes to the database, verify the changes are correct and then undo those changes seamlessly. Triggers will fire, constraints will be respected and more importantly all those things will vanish when you fail to call .Complete().

TransactionScope. It isn't just for failed operations.