Domanda

Qual è il modo più breve per affermare che un attributo è applicato al metodo in c #?

Sto usando nunit-2.5

:)

È stato utile?

Soluzione

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

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

Altri suggerimenti

Non sono sicuro del metodo assert usato da nunit, ma puoi semplicemente usare questa espressione booleana per il parametro che le viene passato (supponendo che tu sia in grado di usare LINQ:

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

Se l'attributo viene applicato, verrà restituito true.

Se vuoi creare una versione generica (e non usare typeof) puoi usare un metodo generico per farlo per te:

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

E poi chiamalo nel tuo metodo assert in questo modo:

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

Per fare ciò con un'espressione, puoi prima definire il seguente metodo di estensione:

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

E poi chiamalo in codice come questo:

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

Nota che non importa quali sono i parametri passati al metodo, dato che il metodo non viene mai chiamato, ha semplicemente bisogno dell'espressione.

Un'alternativa per nunit 2.5:

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

Assert.That(methodInfo, Has.Attribute(typeof(MyAttribute)));
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top