michael
michael

Reputation: 15302

Unit Testing a custom attribute class

I have a custom attribute that is just used to mark a member (no constructor, no properties):

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
public sealed class MyCustomAttribute : Attribute { }

How would I unit test this? And, to clarify... I know the 'what', but not the 'how'

I assume there is a way to unit test it to ensure the proper AttributeUsage is in place? So how could I do this? Every time I create a mock class and try to add the attribute to the wrong thing it won't let me compile, so how can I create a bad mock class to test?

Upvotes: 15

Views: 15394

Answers (1)

myermian
myermian

Reputation: 32525

You would not create a mock class to test this. Instead, you would simply test the attribute class itself to see if it has the proper AttributeUsageAttribute attribute properties. whew, what a mouthful

[TestMethod]
public void Is_Attribute_Multiple_False()
{
    var attributes = (IList<AttributeUsageAttribute>)typeof(MyCustomAttribute).GetCustomAttributes(typeof(AttributeUsageAttribute), false);
    Assert.AreEqual(1, attributes.Count);

    var attribute = attributes[0];
    Assert.IsFalse(attribute.AllowMultiple);
}

// Etc.

Upvotes: 20

Related Questions