简体   繁体   中英

How to unit test attributes with MsTest using C#?

如何使用C#测试MsTest的类属性和方法属性的存在?

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;
}

Use reflection, for example here is one in nunit + c#, which be easily adapted 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's answer below for improved attribute check, HasAttribute

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 tests like this:

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

This way you don't need to use if/else/foreach or other logic in your test methods. Thus they become far more clear and readable.

HTH
Thomas

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM