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

时间:2017-01-05 19:37:27

标签: c# .net unit-testing visual-studio-2013 nunit

是否可以将解决方案概括为适用于任何类型?

有一个很好的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)

是否可以将解决方案概括为适用于任何类型?

1 个答案:

答案 0 :(得分:2)

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