I have just recently discovered the [TestCase] attribute of NUnit. With careful use it can drastically reduce the number of test methods you need to write. For my needs on a recent project I wanted to check field values which were being pulled from my database. What I’ve come up with is a simple extension to the NUnit Assert class which allows me to write test code such as …
[TestCase(0, "Forename", "Antony")]
[TestCase(0, "Surname", "Scott")]
[TestCase(0, "TwitterUserName", "antony_scott")]
public void ExampleTest(int index, string fieldname, object expectedValue)
{
var result = GetPersonDetails();
var list = result.ToList();
Assert.IsFieldEqual(list.ElementAt(index), fieldname, expectedValue);
}
This gives me a very compact and easy to understand test with great visibility of any fields which are being pulled from the database correctly. All this is nothing new, as I’ve blogged about it previously here.
What I’ve added is the ability to dig into a structure like so …
[TestCase(0, "Forename", "Antony")]
[TestCase(0, "Surname", "Scott")]
[TestCase(0, "Twitter.UserName", "antony_scott")]
public void ExampleTest(int index, string fieldname, object expectedValue)
{
var result = GetPersonDetails();
var list = result.ToList();
Assert.IsFieldEqual(list.ElementAt(index), fieldname, expectedValue);
}
In case you can’t see any difference, it’s the “dot” in the 3rd test case.
Here is the “extension” of the Assert class which makes it possible …
public class Assert : NUnit.Framework.Assert
{
public static void IsFieldEqual(object obj, string propertyName, object expectedValue)
{
var type = obj.GetType();
var dotIndex = propertyName.IndexOf('.');
if (dotIndex != -1)
{
var innerObjName = propertyName.Substring(0, dotIndex);
var innerPropName = propertyName.Substring(dotIndex + 1);
var innerProp = type.GetProperty(innerObjName);
var innerObj = innerProp.GetValue(obj, null);
IsFieldEqual(innerObj, innerPropName, expectedValue);
}
else
{
var prop = type.GetProperty(propertyName);
var actualValue = prop.GetValue(obj, null);
AreEqual(expectedValue, actualValue);
}
}
}






