Unit Testing and Integration Testing with your database

by Cliff 12. January 2008

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.

Cliff Gray's Info

Cliff Gray
Developer/Founder GrayTechnology.com.

E-mail me Send mail

Authors

Calendar

<<  April 2019  >>
MoTuWeThFrSaSu
25262728293031
1234567
891011121314
15161718192021
22232425262728
293012345

View posts in large calendar

Blogroll

Download BlogEngine.NET

Download at CodePlex

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2019

Subscribe