My Adsense

Friday, September 7, 2012

Using TransactionScope in TestMethod

For the last two years or more, I have been doing TDD in my pet projects and professional works (where possible). In these days, there were many cases where I needed to test the CRUD operations for the database.
As being the purist TDD practitioner, I never wanted to leave my dummy data into the database since it might cause a vulnerable situation of the live database. So, I always needed to delete the data I inserted for the test purpose.
Suppose, i want to test a GetAll method of the gateway which will bring all of the data of that table from database. To test this method, I need to insert some fake data first in the database, then call the GetAll method. Then I may Assert that the count of the fetched data is more than one.
But why I need to insert some dummy data before calling the GetAll method? Its because you never know whether your real time live database will have data on that table or not. If you don't insert some dummy data, your GetAll test method will fail.
So, I needed to insert some dummy data before calling the GetAll method.

But according to the very basic rule of TDD, you must not leave your test data into the database. So to maintain this rule, I needed to delete those also. So i called the Delete method of the same gateway to delete/clear the dummy data from the database.

But as you are thinking, it is not a good way to clear my dummy data. To make it better approached, we can use TransactionScope instead of deleting the data manually.

Using this scope inside of a method, we don't need to delete the data we inserted manually. After the execution of the TransactionScope block/scope, the inserted data will be reverted back from the database which means automatically deleted from the database. So, since we don't need to delete manually, instead we will use the TransactionScope, the code will be like below.

But what happens if we need to insert the fake data in the TestInitialize method? I didn't explore that yet. I will write another post later on that idea.

No comments: