Unit Testing and Integration Testing with your database

I like to do a combination of unit and integration testing with my projects.  When testing code that update the database you need to account for the state of your databse.  If you want repeatable tests, you either need to use stubs or mocks or find a way to return your databse to the state it was in prior to your tests running.

 One approach that I have been using with success is leveraging the System.Transaction name space within my tests that update the database.  Below is some sample code using the NUnit testing framework.  By wrapping the code that updates the database within a transaction (using (...)) the save operation is rolled back:

 /// <summary>
/// Transaction is not "completed" so gets rolled back preventing
/// test data from being persisted to db.
/// </summary>
[Test]
public void Should_Insert_A_New_Info_Object_Into_DB()
{
using (TransactionScope transScope = new TransactionScope())
{
string testDateTime = DateTime.Now.ToString();
Info info = AddTestRecord(testDateTime);
Assert.IsTrue(info.Subject == "Subject: " + testDateTime);
info.Save();
Assert.IsTrue(info.Subject == "Subject: " + testDateTime);

}

}

Hope people find this technique useful.

Add comment