The primary concern about Database driven Unit testing is to maintain the test database intact. To elaborate, suppose we have an add
method that adds customer
information in the database and we have a get
method that actually returns a list of customer
from database.
So we will have a different Unit test method for AddCustomer()
and GetCustomer()
.
Now in order to pass the GetCustomer()
method as a test case, we have decided that it will return exactly 3 records and we have setup our test database in such a way to meet our test criterion.
The problem will be raised if we test the AddCustomer()
method before GetCustomer()
method as AddCustomer()
method will add one customer
and our GetCustomer()
method will return 4 records that will fail its test case.
In order to overcome such a situation, we can use the power of TransactionScope
Object.
In order to use this, you must include System.Transactions
in the Unit Test Project references and add System.Transactions
in the reference section.
In the class generated by VSTS Unit Test wizard, you can see one region commented like below:
#region Additional test attributes
#endregion
From here, just uncomment MyTestInitialize()
and MyTestCleanup()
method.
Now, declare one global variable of TransactionScope
Object write the body of the methods like below:
TransactionScope ts;
[TestInitialize()]
public void MyTestInitialize()
{
ts = new TransactionScope();
}
[TestCleanup()]
public void MyTestCleanup()
{
ts.Dispose();
}
After this, before executing any Unit Test method, MyTestInitialize()
method will be called where a new instance of TransactionScope
will be created and after executing the Unit test method, the object will be disposed which will ultimately rollback all the changes committed by the Unit test method keeping our test database intact.
Happy testing!