如何在运行时为含自定义特性的方法自动添加NUnit Category特性
解决方案:让NUnit自动识别自定义特性或动态添加Category分类
方案一:让NUnit直接识别SomeAttribute(最优解)
NUnit支持通过实现ITraitAttribute接口,让自定义特性直接被识别为测试分类,无需额外添加Category特性。只需要修改你的SomeAttribute实现即可:
using NUnit.Framework; using System.Collections.Generic; public class SomeAttribute : Attribute, ITraitAttribute { public IEnumerable<KeyValuePair<string, string>> Traits { get { // 返回Category键值对,NUnit会自动识别为分类 yield return new KeyValuePair<string, string>("Category", "SomeAttribute"); } } }
效果说明
- 所有标记了
[SomeAttribute]的类或方法,会自动被NUnit归到SomeAttribute分类下 - 原有已添加的
Category特性(比如示例中的SlowTest)依然生效,测试会同时出现在多个分类中 - 完全不需要开发者手动添加
[Category("SomeAttribute")],新方法只加[SomeAttribute]即可
方案二:动态添加Category特性(兼容特殊场景)
如果因为某些限制不能修改SomeAttribute的继承结构,可以通过NUnit的扩展机制实现动态特性注入。不过这个方案相对复杂,需要编写NUnit扩展:
- 实现
ITestDecorator接口,扫描测试类/方法上的SomeAttribute - 在装饰器中为测试添加
Categorytrait
示例代码(扩展实现):
using NUnit.Framework; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; public class SomeAttributeCategoryDecorator : ITestDecorator { public TestDecoratorResult Decorate(Test test, ITest target) { // 检查当前测试是否标记了SomeAttribute if (test.TypeInfo?.Type?.GetCustomAttributes(typeof(SomeAttribute), true).Length > 0 || test.Method?.MethodInfo?.GetCustomAttributes(typeof(SomeAttribute), true).Length > 0) { // 添加Category trait test.Properties.Add("Category", "SomeAttribute"); } return new TestDecoratorResult(test); } }
之后需要在NUnit配置文件中注册该扩展,让NUnit加载生效。这种方案不如方案一简洁,优先推荐方案一。
内容的提问来源于stack exchange,提问作者Jonathan Hansen
相关产品推荐
相关产品推荐

