Reflection Based Assert with NUnit

I recently wrote about using reflection to check for null values in conjunction with the TestCase attribute. I’ve just taken this a step further by creating a derived Assert class …

public class Assert : NUnit.Framework.Assert
    public static void IsFieldEqual(object obj, string propertyName, object expectedValue)
        var type = obj.GetType();
        var prop = type.GetProperty(propertyName);
        var actualValue = prop.GetValue(obj, null);
        AreEqual(expectedValue, actualValue);

This allows me to write tests to check the value of each field in a result object and have the assert fail on the specific field, it also doesn’t stop the other field being tested. So, using the TestCase attribute I can write tests such as this …

[TestCase("Forename", "Antony")]
[TestCase("Surname", "Scott")]
public void example_test(string fieldname, object expectedValue)
    // Arrange
    Context.AddPerson(new Person { ID = 1, Forename = "Antony", Surname = "Scott" });

    // Act
    var result = Service.GetPerson(1);

    // Assert
    Assert.IsFieldEqual(result, fieldname, expectedValue);

Obviously this is an over-simplified example. But, the idea is that I can now have a complex object being loaded up by an integration test into my database. I then use a Service of some kind (what I’m testing) to query my database and I can then make sure all the correct details have been retrieved from the database.


One response to “Reflection Based Assert with NUnit

  1. Pingback: antony_scott » Blog Archive » NUnit Assert extension to check any property of any object

Leave a Reply

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

You are commenting using your 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