Rollback attribute for NUnit and Entity framework

For integration testing it is very useful to wrap the tests in database transaction, and at the end of the test you just rollback the transaction, so any changes happened inside of the test are not persisted. And the next test run will be running on untouched data.

This is how the attribute looks:

using System;
using System.Transactions;
using NUnit.Framework;

/// <summary>
/// Rollback Attribute wraps test execution into a transaction and cancels the transaction once the test is finished.
/// You can use this attribute on single test methods or test classes/suites
/// </summary>
public class RollbackAttribute : Attribute, ITestAction
{
    private TransactionScope transaction;

    public void BeforeTest(TestDetails testDetails)
    {
        transaction = new TransactionScope();
    }

    public void AfterTest(TestDetails testDetails)
    {
        transaction.Dispose();
    }

    public ActionTargets Targets
    {
        get { return ActionTargets.Test; }
    }
}

Nothing fancy, just used NUnit’s ability to create custom attributes.

The tests will look like

[Test, Rollback]
public void YourTest() {
    // test method body
}

Alternatively you can apply Rollback attribute on the test suite and every test will be wrapped into a transaction automatically. Save you littering Rollback attribute on all the test methods.

[TestFixture, Rollback]
public class ClassUnderTestTests{
   // Test methods
}

Enjoy!