如何使用C#?
使用MsTest测试类属性和方法属性的存在答案 0 :(得分:8)
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;
}
答案 1 :(得分:4)
使用反射,例如这里是nunit + c#中的一个,可以很容易地适应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
答案 2 :(得分:1)
沿着以下几行写自己两个辅助函数(使用反射):
public static bool HasAttribute(TypeInfo info, Type attributeType)
public static bool HasAttribute(TypeInfo info, string methodName, Type attributeType)
然后你可以编写这样的测试:
Assert.IsTrue(HasAttribute(myType, expectedAttribute));
这样您就不需要在测试方法中使用if / else / foreach或其他逻辑。因此,它们变得更加清晰和可读。
HTH
托马斯