属性がC#のメソッドに適用されていることをアサートする最短の方法は何ですか?
-
11-07-2019 - |
質問
C#のメソッドに属性が適用されていることをアサートする最短の方法は何ですか?
nunit-2.5を使用しています
:)
解決
MethodInfo mi = typeof(MyType).GetMethod("methodname");
Assert.IsFalse (Attribute.IsDefined (mi, typeof(MyAttributeClass)));
他のヒント
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>();
メソッドが呼び出されることは決してないため、メソッドに渡されるパラメーターが何であるかは重要ではないことに注意してください。
nunit 2.5の代替:
var methodInfo = typeof(MyType).GetMethod("myMethod");
Assert.That(methodInfo, Has.Attribute(typeof(MyAttribute)));
所属していません StackOverflow