2009-03-12 4 views

答えて

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

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

を私はNUnitのは、使用していますAssertメソッドのわからないんだけど、あなたは、単にそれに渡されたパラメータのため、このブール式を使用することができます(あなたは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メソッドでそれを呼び出す:あなたはあなたのためにこれを行うには、一般的な方法を使用することができます

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

メソッドに渡されるパラメータが何であるかは関係ありません。メソッドが呼び出されないため、式が必要です。

+0

呼び出しがAssert.IsTrueです - ところで、彼は私が文字列とメソッドの情報NPを得ることができMETHODINFO – eglasius

+0

のホールドを取得する方法を知らないかもしれません。表現アプローチを望んでいた。誰かがこの種のテストのためのコードを既に持っているかもしれないと思った。 –

+0

傷みのある方はご遠慮ください。文字列はこの質問には問題ありません。 –

0

代替NUnitの2.5のために:

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

Assert.That(methodInfo, Has.Attribute(typeof(MyAttribute))); 
関連する問題