How to unit test attributes using MsTest using C #?

How to check for class attributes and method attributes using MsTest using C #?

+7
source share
3 answers

C # Extension method for checking attributes

public static bool HasAttribute<TAttribute>(this MemberInfo member) where TAttribute : Attribute { var attributes = member.GetCustomAttributes(typeof(TAttribute), true); return attributes.Length > 0; } 
+8
source

Use reflection, for example, here is one in nunit + C # that easily adapts to MsTest.

 [Test] public void AllOurPocosNeedToBeSerializable() { Assembly assembly = Assembly.GetAssembly(typeof (PutInPocoElementHere)); int failingTypes = 0; foreach (var type in assembly.GetTypes()) { if(type.IsSubclassOf(typeof(Entity))) { if (!(type.HasAttribute<SerializableAttribute>())) failingTypes++; Console.WriteLine(type.Name); //whole test would be more concise with an assert within loop but my way //you get all failing types printed with one run of the test. } } Assert.That(failingTypes, Is.EqualTo(0), string.Format("Look at console output for other types that need to be serializable. {0} in total ", failingTypes)); } //refer to Robert answer below for improved attribute check, HasAttribute 
+4
source

Write yourself two helper functions (using reflection) along these lines:

 public static bool HasAttribute(TypeInfo info, Type attributeType) public static bool HasAttribute(TypeInfo info, string methodName, Type attributeType) 

Then you can write the tests as follows:

 Assert.IsTrue(HasAttribute(myType, expectedAttribute)); 

This way you do not need to use if / else / foreach or other logic in your testing methods. Thus, they become much more understandable and readable.

NTN
Thomas

+1
source

All Articles