请告诉我断言一个属性应用于方法在C#的最短途径?

我使用NUnit-2.5

:)

有帮助吗?

解决方案

MethodInfo mi = typeof(MyType).GetMethod("methodname");    

Assert.IsFalse (Attribute.IsDefined (mi, typeof(MyAttributeClass)));

其他提示

我不知道NUnit的使用断言方法,但你可以简单地使用传递给它的参数,这个布尔表达式(假设你能够使用LINQ:

methodInfo.GetCustomAttributes(attributeType, true).Any()

如果应用了属性,那么它将返回true。

如果你想使一个普通版本(而不是使用typeof运算),你可以使用一个通用的方法来为你做这一点:

static bool IsAttributeAppliedToMethodInfo<T>(this MethodInfo methodInfo) 
    where T : Attribute
{
    // If the attribute exists, then return true.
   return methodInfo.GetCustomAttributes(typeof(T), true).Any();
}

和然后调用它在断言方法,如下所示:

<assert method>(methodInfo.IsAttributeAppliedToMethodInfo<MyAttribute>());

要使用表达式做到这一点,可以先定义下面的扩展方法:

public static MethodInfo 
    AssertAttributeAppliedToMethod<TExpression, TAttribute>
    (this Expression<T> expression) where TAttribute : Attribute
{
    // Get the method info in the expression of T.
    MethodInfo mi = (expression.Body as MethodCallExpression).Method;

    Assert.That(mi, Has.Attribute(typeof(TAttribute)));
}

和然后调用它在这样的代码:

(() => Console.WriteLine("Hello nurse")).
    AssertAttributeAppliedToMethod<MyAttribute>();

请注意,它并不重要传递给该方法的参数是,因为该方法不会被调用,它仅需要表达。

有NUnit的2.5的替代:

var methodInfo = typeof(MyType).GetMethod("myMethod");

Assert.That(methodInfo, Has.Attribute(typeof(MyAttribute)));
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top