views:

116

answers:

3

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

I'm using nunit-2.5

:)

+1  A: 

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.

casperOne
the call is Assert.IsTrue - btw, he might not know how to get a hold of the methodInfo
eglasius
I can get method info np with strings. Was hoping for an expression approach. Thought someone might have some code already for this type of test.
TheDeeno
scratch that request. Strings are fine for this question.
TheDeeno
+2  A: 
MethodInfo mi = typeof(MyType).GetMethod("methodname");    

Assert.IsFalse (Attribute.IsDefined (mi, typeof(MyAttributeClass)));
Frederik Gheysels
A: 

An alternative for nunit 2.5:

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

Assert.That(methodInfo, Has.Attribute(typeof(MyAttribute)));
TheDeeno