Pregunta

¿Cuál es la forma más corta de afirmar que un atributo se aplica al método en c #?

Estoy usando nunit-2.5

:)

¿Fue útil?

Solución

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

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

Otros consejos

No estoy seguro del método de aserción que usa nunit, pero simplemente puede usar esta expresión booleana para el parámetro que se le pasa (suponiendo que pueda usar LINQ:

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

Si se aplica el atributo, devolverá verdadero.

Si desea hacer una versión genérica (y no usar typeof), puede usar un método genérico para hacer esto por usted:

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

Y luego llámalo en tu método de aserción de la siguiente manera:

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

Para hacer esto con una expresión, puede definir primero el siguiente método de extensión:

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

Y luego llámalo en un código como este:

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

Tenga en cuenta que no importa cuáles sean los parámetros que se pasan al método, ya que el método nunca se llama, simplemente necesita la expresión.

Una alternativa para nunit 2.5:

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

Assert.That(methodInfo, Has.Attribute(typeof(MyAttribute)));
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top