Thursday, February 28, 2008

Unit Test Object Properties

Unit testing of entities is something that never gets done very well for a number of reasons, the objects are pretty simplistic, developers get board righting that type of code, etc. It seems that one area unit tests of this type of business object fails is in testing their properties. The test covers setting and retrieving the properties but what about Business Objects with CRUD behavior? What about testing Data Access layer save functionality. Just because the save method does not error on you does not mean the save works. To really have a good unit test you need to save the object and then get the object again and compare all the properties to make sure each property was saved as expected.

To test each property I often see developers writing code that does a one to one compare on the two objects (the object they tried to save and the object that was saved). This gets boring really quickly and can explain why a lot of the time you do not see full code coverage. To help make this easier I recently wrote  a simple piece of code to handle all this property comparison. With the code below you can simply pass it two objects of the same type and it will do a property compare on each object to make sure each matching property has the same value.

public void CompareObjectProperties(Object newOjbect, Object dbObject)
    PropertyInfo[] propInfo = newOjbect.GetType().GetProperties();

    foreach (PropertyInfo prop in propInfo)
        PropertyInfo dbPropinfo = dbObject.GetType().GetProperty(prop.Name);
        string newProp = prop.GetValue(newOjbect, null).ToString();
        string dbProp = dbPropinfo.GetValue(dbObject, null).ToString();

        // Make sure each value was saved to the database correctly
        Assert.AreEqual(newProp, dbProp, "The value on the object did not match the value saved to the second object");

No comments: