如何断言方法具有指定的属性 [英] How to assert that a method has a specified attribute
本文介绍了如何断言方法具有指定的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以概括适用于任何类型的解决方案?
有一个很棒的解决方案,用于断言方法中是否存在指定的属性:
There is a wonderful solution to asserting whether a specified attribute exists on a method:
public static MethodInfo MethodOf( Expression<System.Action> expression )
{
MethodCallExpression body = (MethodCallExpression)expression.Body;
return body.Method;
}
public static bool MethodHasAuthorizeAttribute( Expression<System.Action> expression )
{
var method = MethodOf( expression );
const bool includeInherited = false;
return method.GetCustomAttributes( typeof( AuthorizeAttribute ), includeInherited ).Any();
}
用法将是这样的:
var sut = new SystemUnderTest();
var y = MethodHasAuthorizeAttribute(() => sut.myMethod());
Assert.That(y);
我们如何推广该解决方案并更改以下签名:
How do we generalize this solution and change the signature from:
public static bool MethodHasAuthorizeAttribute(Expression<System.Action> expression)
类似这样:
public static bool MethodHasSpecifiedAttribute(Expression<System.Action> expression, Type specifiedAttribute)
是否可以概括适用于任何类型的解决方案?
推荐答案
public static MethodInfo MethodOf(Expression<Action> expression)
{
MethodCallExpression body = (MethodCallExpression)expression.Body;
return body.Method;
}
public static bool MethodHasAttribute(Expression<Action> expression, Type attributeType)
{
var method = MethodOf(expression);
const bool includeInherited = false;
return method.GetCustomAttributes(attributeType, includeInherited).Any();
}
或使用泛型:
public static bool MethodHasAttribute<TAttribute>(Expression<Action> expression)
where TAttribute : Attribute
{
var method = MethodOf(expression);
const bool includeInherited = false;
return method.GetCustomAttributes(typeof(TAttribute), includeInherited).Any();
}
您会这样称呼:
var sut = new SystemUnderTest();
y = MethodHasAttribute<AuthorizeAttribute>(() => sut.myMethod());
That(y);
这篇关于如何断言方法具有指定的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文