How to assert that a method has a specified attribute

我只是一个虾纸丫 提交于 2019-12-10 11:54:04

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/41493289/how-to-assert-that-a-method-has-a-specified-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!