A classic problem to unit testing code that modifies the underlying data in the database tables is that you need to find a way to revert back to the original database state so that the tests can be run over and over again.
Using the transaction capabilities provided with the .Net 2.0 framework and a unit testing framework you can achieve this easily.
The process:
- Create a new transaction before each test.
- Dispose (Rollback) the transaction after each test.
using System.Data;
[TestClass]
public class DataProviderTest {
private readonly DataProvider _dp = new DataProvider();
private TransactionScope _transactionScope;
[TestInitialize]
public void TestInitialize() {
_transactionScope = new TransactionScope();
}
[TestCleanup]
public void TestCleanup() {
_transactionScope.Dispose();
}
[TestMethod]
public void InsertTest()
{
// modify the database
...
}
}