Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top