【问题标题】:How to assert that a method has a specified attribute如何断言方法具有指定的属性
【发布时间】:2017-01-05 19:37:27
【问题描述】:

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

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

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

【问题讨论】:

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


    【解决方案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();
    }
    

    或者使用泛型:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-04
      • 2022-03-31
      • 1970-01-01
      • 1970-01-01
      • 2018-03-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多