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가 반환됩니다.
일반 버전 (유형을 사용하지 않음)을 만들려면 일반 메소드를 사용하여이를 수행 할 수 있습니다.
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