views:

355

answers:

2

I was thinking it would be nice to create a base class for NUnit test fixtures that opens a TransactionScope during the SetUp phase, then rolls back the transaction during tear down. Something like this:

    public abstract class TestFixtureBase
{
 private TransactionScope _transaction;

 [TestFixtureSetUp]
 public void TestFixtureSetup()
 {
  _transaction = new TransactionScope();
 }

 [TestFixtureTearDown]
 public void TestFixtureTearDown()
 {
  if (_transaction != null)
  {
   _transaction.Dispose();
  }
 }
}

Do you think this is a good idea?

Obviously the database is just a test database, not a live database, but it would still be annoying if it filled up with junk data from the unit tests.

What do other people do when running unit tests that involve a lot of data access?

+4  A: 

You want to be careful here. TransactionScope is going to promote the transaction to a distributed transaction if you open up more than one connection to the database. I find that it is easier just to write some simple SQL that clears out the tables of interest to my test class before I start running the test.

EDIT: Normally I would call any test that touches the database an integration test since it involves another system. Typically, I will mock out the database when unit testing my code.

[TestSetup]
public void Setup()
{
   foreach (string table in new string[] { "table1", "table2" })
   {
        ClearTable( table );
   }
}

private void ClearTable( string table )
{
     ...standard stuff to set up connection...
     SqlCommand command = connection.CreateCommand() );
     command.CommandText = "delete from " + table;
     command.ExecuteNonQuery();
     ... stuff to clean up connection...
}
tvanfosson
+ 1 to mock out data access... unless you are actually testing the DAL implementation.
Gishu
+1  A: 

I've used XtUnit It automatically rolls back at the end of a unit test. You can simply add a [Rollback] attribute to the test. It's an extension to NUnit or MbUnit

Cohen