如何断言方法具有指定的属性

How to assert that a method has a specified attribute

是否可以推广适用于任何类型的解决方案?

有一个很棒的solution断言方法上是否存在指定的属性:

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

我们如何推广此解决方案并更改签名:

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