Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Unit Testing C# Custom Attributes with NUnit - Part 2

5.00/5 (2 votes)
27 Jul 2011CPOL1 min read 12.4K  
Unit Testing C# Custom Attributes with NUnit

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:

C#
[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 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.

C#
Assert.IsNotNull(propertyInfo);

becomes:

C#
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 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.

C#
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)