Alex Gordon
Alex Gordon

Reputation: 60861

How to assert that a method has a specified attribute

Is it possible to generalize the solution to work for any type?

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

The usage would be something like this:

        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)

to something like this:

public static bool MethodHasSpecifiedAttribute(Expression<System.Action> expression, Type specifiedAttribute)

Is it possible to generalize the solution to work for any type?

Upvotes: 0

Views: 207

Answers (1)

Jason Boyd
Jason Boyd

Reputation: 7029

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

Or with generics:

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

Which you would call like this:

var sut = new SystemUnderTest();
y = MethodHasAttribute<AuthorizeAttribute>(() => sut.myMethod());
That(y);

Upvotes: 2

Related Questions