如何断言方法具有指定的属性
是否可以将解决方案概括为适用于任何类型?
有一个很好的解决方案来断言方法上是否存在指定的属性:
public static MethodInfo MethodOf( Expression expression ) { MethodCallExpression body = (MethodCallExpression)expression.Body; return body.Method; } public static bool MethodHasAuthorizeAttribute( Expression 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);
我们如何推广此解决方案并更改签名:
public static bool MethodHasAuthorizeAttribute(Expression expression)
这样的事情:
public static bool MethodHasSpecifiedAttribute(Expression expression, Type specifiedAttribute)
是否可以将解决方案概括为适用于任何类型?
public static MethodInfo MethodOf(Expression expression) { MethodCallExpression body = (MethodCallExpression)expression.Body; return body.Method; } public static bool MethodHasAttribute(Expression expression, Type attributeType) { var method = MethodOf(expression); const bool includeInherited = false; return method.GetCustomAttributes(attributeType, includeInherited).Any(); }
或者使用generics:
public static bool MethodHasAttribute(Expression 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(() => sut.myMethod()); That(y);