NUnit Assert extension to check any property of any object

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);
        }
    }
}
Advertisements

One response to “NUnit Assert extension to check any property of any object

  1. Pingback: Using Moq to check the values of an object passed to a method « antony_scott

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s