[英]Whats the shortest way to assert that an attribute is applied to method in c#?
断言将属性应用于c#中的方法的最短方法是什么?
我正在使用nunit-2.5
:)
MethodInfo mi = typeof(MyType).GetMethod("methodname");
Assert.IsFalse (Attribute.IsDefined (mi, typeof(MyAttributeClass)));
我不确定nunit使用的assert方法,但是您可以简单地将此布尔表达式用作传递给它的参数(假设您可以使用LINQ:
methodInfo.GetCustomAttributes(attributeType, true).Any()
如果应用了该属性,则它将返回true。
如果要创建通用版本(而不使用typeof),则可以使用通用方法为您执行此操作:
static bool IsAttributeAppliedToMethodInfo<T>(this MethodInfo methodInfo)
where T : Attribute
{
// If the attribute exists, then return true.
return methodInfo.GetCustomAttributes(typeof(T), true).Any();
}
然后在您的assert方法中调用它,如下所示:
<assert method>(methodInfo.IsAttributeAppliedToMethodInfo<MyAttribute>());
为此,您可以先定义以下扩展方法:
public static MethodInfo
AssertAttributeAppliedToMethod<TExpression, TAttribute>
(this Expression<T> expression) where TAttribute : Attribute
{
// Get the method info in the expression of T.
MethodInfo mi = (expression.Body as MethodCallExpression).Method;
Assert.That(mi, Has.Attribute(typeof(TAttribute)));
}
然后在这样的代码中调用它:
(() => Console.WriteLine("Hello nurse")).
AssertAttributeAppliedToMethod<MyAttribute>();
请注意,传递给该方法的参数是什么都没有关系,因为从不调用该方法,它只需要表达式。
nunit 2.5的替代方法:
var methodInfo = typeof(MyType).GetMethod("myMethod");
Assert.That(methodInfo, Has.Attribute(typeof(MyAttribute)));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.