Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / operating-systems / Windows

Unit Testing C# Custom Attributes with NUnit Part 4

0.00/5 (No votes)
18 Aug 2011CPOL1 min read 11.8K  
Unit Testing C# Custom Attributes with NUnit

In Unit Testing C# Custom Attributes with NUnit Part 3, towards the end I showed the following code:

C#
Assert.That(MethodBase.GetCurrentMethod(), 
            Has.Attribute<FunkyAttribute>().Property("SettingOne").TypeOf<int>());

to test the type of a property on an attribute. As it turns out, this does not actually do that. Instead, it tests the type of the value returned from the property. What's happening is that the object returned from Property() isn't some of meta-object representing a property but is the actual value of the property.

In the case above, it amounts to the same thing. As the property type is an int even if it has not been set, the value will be 0 of which type is int. However, if it's a reference type (quite likely a string) or a nullable type, the value can be null. E.g.

C#
Assert.That(MethodBase.GetCurrentMethod(), 
	    Has.Attribute<FunkyAttribute>().Property("FunkyName").TypeOf<string>());

which causes the following when run:

C#
AttrTestV3.FunkyTester.TestThatTheTypeOfFunkyNameWhenNotSetIs_string:
  Expected: attribute AttrTestDefs.FunkyAttribute property FunkyName <System.String>
  But was:  <AttrTestDefs.FunkyAttribute>

It seems that when there is no value Property() which tests for the presence of the specified property name and implicitly returns the value of the property (if found) has nothing to return so for some reason the attribute type obtained from the call Has.Attribute() is returned.

Currently, there is no way with NUnit to handle this case. I started a thread on the NUnit discussion group which discusses this issue and it seems like the authors of NUnit have some plans.

As an interim solution, if the property is optional for a custom attribute, then in the fixture make sure a value is assigned. In the case above:

C#
[Test]
[Funky(FunkyName = "dummy")]
public void TestThatTheTypeOfFunkyNameWhenNotSetIs2_string()
{
    Assert.That(MethodBase.GetCurrentMethod(),
        	Has.Attribute<FunkyAttribute>().Property("FunkyName").TypeOf<string>());
}

I think that's the end again:-)

License

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