Question

Whats the shortest way to assert that an attribute is applied to method in c#?

I'm using nunit-2.5

:)

Was it helpful?

Solution

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

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

OTHER TIPS

I'm not sure of the assert method that nunit uses, but you can simply use this boolean expression for the parameter that is passed to it (assuming you are able to use LINQ:

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

If the attribute is applied, then it will return true.

If you want to make a generic version (and not use typeof) you can use a generic method to do this for you:

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

And then call it in your assert method like so:

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

To do this with an expression, you can define the following extension method first:

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

And then call it in code like this:

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

Note that it doesn't matter what the parameters that are passed to the method are, as the method is never called, it simply needs the expression.

An alternative for nunit 2.5:

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

Assert.That(methodInfo, Has.Attribute(typeof(MyAttribute)));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top