Unit Testing on Your Database
When unit testing on your database, you will run into a common problem.
Rolling back.
So you want to do some unit tests, and then you want to reset your database back to the nice squeaky clean version that doesn’t have half failed unit tests.
So how can you do this?
There are many ways to achieve this.
The best way I found (requires Win XP SP2 or Windows Server 2003) is to use Roy’s Unit Testing Rollback Attribute. Simply inherit his class, add a "DataRollback" attribute, and you are good to go. Using some complicated Interception logic and Enterprise Services (COM+) it rolls back all the database work that was done. It’s super easy to implement. Here is some sample code that shows you just how easy it is. You just have to download XtUnit (an extension to NUnit) to do this. (Full source code available)
using System;
using System.Data;
using System.Collections.Generic;
using System.Text;
using TeamAgile.ApplicationBlocks.Interception.UnitTestExtensions;
using NUnit.Framework;
using System.Data.SqlClient;
using Microsoft.ApplicationBlocks.Data;
namespace DBTest
{
///<summary>
/// Test roll back functionality.
///</summary>
[TestFixture]
public class RollbackTest : ExtensibleFixture
{
[Test, DataRollBack]
[Category("Database")]
public void TestInsert()
{
//this method will be performed inside a COM+ transaction
//this requires windows XP SP2 or better
//Windows Server 2003 works as well.
string strCnn = "your_conn_string";
Guid random = Guid.NewGuid();
string sqlI = string.Format(@"insert into log4net (message,date,thread,level,logger) values ('{0}',getdate(),'{1}','Debug','Test')", random.ToString(), System.Threading.Thread.CurrentThread.GetHashCode());
SqlHelper.ExecuteNonQuery(strCnn, CommandType.Text, sqlI);
string sqlS = string.Format(@"select count(*) from log4net where message='{0}'", random.ToString());
int rowcount = (int)SqlHelper.ExecuteScalar(strCnn, CommandType.Text, sqlS);
Assert.That(rowcount > 0, "Cannot find {0}", random.ToString());
}
}
}
Related Reading:
Other Interesting Posts
2 Responses to Unit Testing on Your Database
Leave a Reply Cancel reply
-
Articles
- January 2011
- April 2010
- March 2010
- February 2010
- January 2010
- August 2009
- July 2009
- June 2009
- May 2009
- April 2009
- February 2009
- December 2008
- November 2008
- October 2008
- July 2008
- June 2008
- May 2008
- April 2008
- March 2008
- February 2008
- December 2007
- November 2007
- October 2007
- September 2007
- August 2007
- July 2007
- June 2007
- May 2007
-
Meta








Rails actually solves this problem by having a dedicated test database. Whenever you run a test, it wipes out the test DB, rebuilds the data (you can specify some fixed data in there), and runs the tests.
Very cool.
Nice! Thanks for the comment brother