Unit test with rollback pattern


For the person who is not familiar with Unit Testing yet. We basically have two options to do unit testing against functions that do CRUD operations, probably with some easy and/or complex logic. They are Mock and Rollback patterns. To keep this post short, I wouldn’t go into details of what the Mock is but you can search it yourself, there is a bunch of contents out there. This post will go with the Rollback pattern.  So, what is the Rollback pattern?

Well, we need to rollback what we did change to the data in database by the function that the unit test invokes. Including operation(s) in unit test that we may need to execute and it does change data in database.

Pretty simple example. If we run this below test twice, Assert will fail in the second run because the user Id 1 was already deleted by the first run.

 [TestMethod]
 public void DeleteUser_Test()
 {
    int userId = 1;

    bool isDeleted = service.DeleteUser(userId);

    Assert.IsTrue(isDeleted);
 }

The easiest way is to use TransactionScope to wrap it up.

 [TestMethod]
 public void DeleteUser_Test()
 {
    int userId = 1;
    using(TransactionScope ts = new TransactionScope())
    {
       bool isDeleted = service.DeleteUser(userId);

       Assert.IsTrue(isDeleted);
    }
 }

Without calling ts.Complete(), the transaction ts would rollback what DeleteUser function did.

If you are using ORM, you must ensure that it does support TransactionScope. I’m sure that LLBLGen, LinqToSQL, LinqToEntities (Entity Framework) do support.

Also beware of executing the store procedure that creates another transaction inside. If you wrap this calling up in TransactionScope, the TransactionScope does not take over the transaction created inside the store procedure. This means that the TransactionScope couldn’t rollback the transaction inside the store procedure.

I would recommend not to use Rollback Unit test if the testing service executes the store procedure.

Tagged , , , ,

One thought on “Unit test with rollback pattern

  1. […] to my previous post that talked about Unit Test with Rollback Pattern, Entity Framework is one of ORM tool that developer has to learn it to use accurately. So if you […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: