Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 238
michael Avatar asked Jul 12 '11 18:07

michael


People also ask

Which attribute is used to define custom unit test properties in unit testing?

TestOf. The TestOf attribute lets the developer specify the class that is being tested. The attribute can be applied to both a fixture or individual tests. This attribute can be used by certain IDE to bind tests to tested components.


1 Answers

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.
like image 149
myermian Avatar answered Nov 15 '22 18:11

myermian