在c#中断言属性已应用于方法的最短方法是什么?
我使用的是nunit-2.5
:)
发布于 2009-03-12 18:44:52
MethodInfo mi = typeof(MyType).GetMethod("methodname");
Assert.IsFalse (Attribute.IsDefined (mi, typeof(MyAttributeClass)));发布于 2009-03-12 18:38:01
我不确定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>();请注意,传递给该方法的参数是什么并不重要,因为该方法从未调用过,它只需要表达式。
发布于 2009-03-12 18:56:13
nunit 2.5的替代方案:
var methodInfo = typeof(MyType).GetMethod("myMethod");
Assert.That(methodInfo, Has.Attribute(typeof(MyAttribute)));https://stackoverflow.com/questions/639913
复制相似问题