我正在使用NUnit,并在我的某些测试上应用了类别属性:
[Category("FastTest")]
这些测试必须非常快地运行,不超过10秒钟。因此,我还用装饰器来优化它们的性能。
[Timeout(10000)]
现在的问题是:
每当我使用[Category("FastTest")]修饰一个方法时,如何使其自动被[Timeout(1000)]修饰?
public class FastTestAttribyte :TimeoutAttribute
{
protected string categoryName;
public FastTestAttribyte (int timeout):base(timeout)
{
categoryName = "FastTest";
}
public string Name { get return categoryName; }
}
编辑
如果您反编译属性,它将起作用,这就是它的作用。
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple=true, Inherited=true)]
public class CategoryAttribute : Attribute
{
// Fields
protected string categoryName;
// Methods
protected CategoryAttribute()
{
this.categoryName = base.GetType().Name;
if (this.categoryName.EndsWith("Attribute"))
{
this.categoryName = this.categoryName.Substring(0, this.categoryName.Length - 9);
}
}
public CategoryAttribute(string name)
{
this.categoryName = name.Trim();
}
// Properties
public string Name
{
get
{
return this.categoryName;
}
}
}
我认为Nunit将使用反射来获取属性的名称。
FastTestAttribyte
充当CategoryAttribute
?您已反编译了CategoryAttribute
的代码,但尚未查看NUnit如何查看它。仅具有“名称”属性是不够的。 NUnit需要知道您打算将该属性表示为类别。它通过在方法或类上查找CategoryAttribute
来实现这一点。 - Mike TwoName
属性。我怀疑 NUnit 甚至不会考虑查看您自己的属性,可能它有类似这样的代码:var categoryAttributes = testMethodInfo.GetCustomAttributes(typeof(CategoryAttribute)).
这样的代码永远不会找到您的属性。 - Snowbear我理解你的意思/需求,但我认为这是不可能的。你是希望在添加一个属性时,IDE会自动添加另一个属性,或者让nUnit知道一个类别是什么,并为某些类别的测试应用特定的额外属性吗?
听起来像个好主意,但在这种情况下更像是nUnit配置,而不是纯粹的C#属性链接,我不知道是否存在。