Even simpler Database Unit Testing with TransactionScope

Technorati Tags: ,

Roy Osherove has a well read article explaining how to use Enterprise Services to do database testing.  This is a pretty nice solution but if you are using .Net 2  then there is an even simpler way:  Using System.Transactions.TransactionScope.

Some background: When you unit test code that is making changes to a database you want a way to ensure that the database remains consistent between tests.  One way to do that is to wrap the work in a transaction and then roll it back after the test is done.

If you are using .Net 2 then you declare a TransactionScope variable then instantiate it in SetUp method:

private TransactionScope scope;

[SetUp]
public void SetUp()
{
  scope = new TransactionScope(TransactionScopeOption.RequiresNew);
}

Now simple dispose of it in the TearDown method:

[TearDown]
public void TearDown()
{
  scope.Dispose();
}

Any test will now run in a transaction.  If your database code is using multiple connections then you may need to have the MSDTC running (because the transaction will be promoted from a lightweight one to a DTC one), but apart from that you are done.

HTH

Ian

posted @ Monday, July 31, 2006 4:34 PM

Print

Comments on this entry:

# re: Even simpler Database Unit Testing with TransactionScope

Left by SSR at 7/18/2008 1:58 PM
Gravatar
Hi Ian,

That was a very valuable pointer there. But what if the Data Access Layer routine you are testing also has a TransactionScope declared in it ?

-ssr

# sehwoddw

Left by sehwoddw at 8/9/2008 7:55 PM
Gravatar
sehwoddw

# zosgphcu

Left by zosgphcu at 8/9/2008 8:09 PM
Gravatar
zosgphcu

# zbhtmpfx

Left by zbhtmpfx at 8/9/2008 9:46 PM
Gravatar
zbhtmpfx

# zkxxehcr

Left by zkxxehcr at 8/9/2008 10:01 PM
Gravatar
zkxxehcr
Comments have been closed on this topic.
«July»
SunMonTueWedThuFriSat
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678