Cleaning up after unit test that tests your data layer can be pretty tedious. In order to simplify that work using the concept of transactions has been well documented in the book “Test-Driven Development in Microsoft.NET” from James W. Newkirk. However, it still involved some level of code that can be simplified using the concept of TransactionScope.
Here is what you need to add to your test class using MSTest in order to remove/avoid any cleanup code in your unit test:
<span style="color: #0000ff">private</span> TransactionScope TransactionScope { get; set; }
 
[TestInitialize]
<span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> MyTestInitialize()
{
TransactionScope = <span style="color: #0000ff">new</span> TransactionScope(TransactionScopeOption.RequiresNew);
}
 
[TestCleanup]
<span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> MyTestCleanup()
{
TransactionScope.Dispose();
}
This strategy will make sure that database manipulations are reversed automatically without you having to write any additional code within your tests.
For this code to work, you will require .NET 2.0 and you will also need to enable DTC on the machine running your unit test.