Tuesday 26 July 2011

Unit Testing C# Custom Attributes with NUnit Part 2

I thought that my last post about Unit Test C# Custom Attributes with NUnit was going to be the only one.  However, after reading more of the NUnit documentation I found that despite the QuickStart guide using the Classic model the preferred model for working with NUnit is that of Constraints.  As such I thought I ought to change over to this which is what the updated code below shows.

[Test]
[Funky(FunkyName = "RipSnorter")]
public void TestThatNameIsRipSnorter()
{
 TestAttrProperty<FunkyAttribute, string>(MethodBase.GetCurrentMethod(), "FunkyName", "RipSnorter");
}

[Test]
[Funky(SettingOne = 77)]
public void TestThatSettingOneIs77()
{
 TestAttrProperty<FunkyAttribute, int>(MethodBase.GetCurrentMethod(), "SettingOne", 77);
}

// Helpers
private void TestAttrProperty<TAttr, TProp>(MethodBase method, string argName, TProp expectedValue)
{
 object[] customAttributes = method.GetCustomAttributes(typeof(TAttr), false);

 Assert.AreEqual(1, customAttributes.Count());

 TAttr attr = (TAttr)customAttributes[0];

 PropertyInfo propertyInfo = attr.GetType().GetProperty(argName);

 Assert.That(propertyInfo, Is.Not.Null);
 Assert.That(propertyInfo.PropertyType, Is.EqualTo(typeof(TProp)));
 Assert.That(propertyInfo.CanRead, Is.True);
 Assert.That(propertyInfo.CanWrite, Is.True);
 Assert.That(propertyInfo.GetValue(attr, null), Is.EqualTo(expectedValue));
}

The major change is rather that than calling Assert.<Assertion> the Constraint model starts with specifying the object to be tested followed by the test.  Additionally, the Constraint model encourages a Fluent style interface, e.g.

Assert.IsNotNull(propertyInfo);

becomes

Assert.That(propertyInfo, Is.Not.Null);

I'm not going to explain the new model here (the above link has the details) but rather this is to just point out this style which can be contrasted to the sample in the previous post.

In addition I remembered that a far easier way to obtain the current method metadata, i.e. MethodBase was to simply to use reflection by calling MethodBase.GetCurrentMethod() from System.Reflection.

You might also have noticed that in this updated example the FunkyAttribute property Name has become FunkyName.

public class FunkyAttribute : Attribute
{
 public int SettingOne { get; set; }
 public string FunkyName { get; set; }
}

This was to differentiate from the Name property of the PropertyInfo class.

However, this isn't the main reason for part 2.  However, this post seems long enough already so the good bit will come in part 3 which I'll write immediately so not too much waiting around.  A part 4 also emerged!

No comments: