Thursday, March 5, 2009

Current Reading

I'm currently reading Pro WPF in C# 2008 by Matthew MacDonald. So far it seems well written and I'm getting a good feel for WPF. I'm anxious to do my first WPF project but didn't want to just jump in without some background.

However, ultimately you can't learn a technology without jumping in and making a whole bunch of stupid mistakes.


Wednesday, March 4, 2009

Article on Setting Properties Dynamically

For the previous post on NUnit and testing properties using reflection I was indebted to this article. The code examples in this article are in VB.Net.

Testing C# Class Properties With NUnit

In their book Pragmatic Programing Andrew Hunt and David Thomas argue that all programmers should adhere to the DRY principle. DRY stands for do not repeat yourself. Its a daily battle to keep my code library from descending into the usual cut and paste mess of massively duplicated code.

I had a few C# classes that had an high number of properties and I wanted to make sure each property had a unit test to make sure they were assigning correctly. I envisioned this as being massively tedious. I thought that a better approach might be to iterate through the properties using reflection and test them by setting and retrieving test values. This would also mean I wouldn't have to change the unit test if I added, deleted or renamed properties.

The code I came up with is very sketchy and preliminary but it does work. It can be refactored any number of ways to suit invididual tastes. In this unit test the class Patient is being tested.

I'm only testing properties of type String and Integer in this example. You can add any type you want. I am thinking about a way to test these properties that is type independent.

        [Test]
public void Properties()
{
Patient patient = new Patient();
int intTestData = 0;

foreach (string propertyName in GetProperties(new Patient()))
{
Type patientType = patient.GetType();
PropertyInfo property = patientType.GetProperty(propertyName);


string stringTestData;

if (property.PropertyType == typeof(System.String))
{
intTestData++;
stringTestData = String.Format("Testdata{0}", intTestData);

Console.WriteLine(String.Format("Testing property {0} of type {1} with value {2}", propertyName, property.PropertyType.ToString(),stringTestData));

if (property.CanWrite == true && property.CanRead == true)
{
property.SetValue(patient, stringTestData, null);
Assert.AreEqual(stringTestData,property.GetValue(patient,null));
}
}

if (property.PropertyType == typeof(System.Int32))
{
property.SetValue(patient, intTestData, null);
Assert.AreEqual(intTestData, property.GetValue(patient, null));
}
}
}