In the beginning of most projects developers write unit tests. But when project grows it become difficult to manage the unit tests. Tough deadlines are the main culprit for non-maintained unit tests.
You should remember not to commit the transaction. Then the tests will run successfully without keeping any garbage data in database.
Note:
If you have identity data columns for your database tables, these test methods will increase the current identity value since it creates data rows in the database (data will be rollback, but not the identity value of the table). So you may need to execute a script to reset identity column value.
But poor test data management strategy is also a main culprit in non-maintainability of test cases. In a previous project I used TransactionScope avoid writing test data and causing un-manageable test cases
Strategy:
The simple theory is, if we rollback the transaction, test cases will not save any test data to the database. So what I have done is:
- Used a single class to provide test data (yes I used a fixed set of data for testing, if someone needs to generalized this, he/she can use a separate test data in a .XML file or another storage)
- Wrote all database related functionality inside a TransactionScope and did a transaction rollback to avoid data save
Steps:
Used a single class to retrieve test data:
public class TestDataProvider {
public static Employee GetEmployee() {
var employee = new Employee{
Name = "Paul",
DateOfBirth = new DateTime(1980, 5,5),
JoinedDate = new DateTime(2005, 01, 01),
Position = "Engineer"};
return employee;
}
} Wrote all the database related functionality inside a transaction scope and did not commit the rollback:
/// <summary>
///A test for AddEmployee
///</summary>
[TestMethod()]
public void AddEmployeeTest() {
var employee = TestDataProvider.GetEmployee();
using(var ts = new TransactionScope()) {
int newEmployeeID = EmployeeLogic.AddEmployee(employee);
Assert.AreNotEqual(0, newEmployeeID, "Employee Not Saved Properly");
var saved = EmployeeLogic.FindByID(newEmployeeID);
Assert.AreNotSame(saved.Name, employee.Name, "Different Name");
Assert.AreNotSame(saved.DateOfBirth, employee.DateOfBirth, "Different DoB");
//ts.Complete(); - do not complete the transaction
}
}
You should remember not to commit the transaction. Then the tests will run successfully without keeping any garbage data in database.
Note:
If you have identity data columns for your database tables, these test methods will increase the current identity value since it creates data rows in the database (data will be rollback, but not the identity value of the table). So you may need to execute a script to reset identity column value.
No comments:
Post a Comment