Simple database fixture.

Very often we need to write tests which interact with the database. I found that many people are still doing complex clean up manipulation in tear down method. But in most cases it is useless work. All you need to  perform clean up of database after each test is to use TransactionScope. This process is so simple that it is hard to believe that it works. The main idea is to create TransactionScope object in SetUp mehod (Constructor in xUnit) and dispose it in TearDown method (Dispose in xUnit).

Here is an example of database fixture for xUnit test framwork (I'm big fun of this recently released test framework):

using System;

using System.Transactions;

 

namespace IntegrationTests

{

    public class DatabaseFixture: IDisposable

    {

        private readonly TransactionScope transactionScope;

 

        protected DatabaseFixture()

        {

            transactionScope = new TransactionScope(TransactionScopeOption.RequiresNew); 

        }

 

        public void Dispose()

        {

            transactionScope.Dispose();

        }

    }

}


 

No Comments