NUnit 自定义属性同时表现为 TestAttribute 和 CategoryAttribute

NUnit custom attribute behaving as TestAttribute and CategoryAttribute simultaneously

我想知道是否可以创建自定义 NUnit 属性,该属性将作为 CategoryAttribute 同时作为 TestAttribute。

NUnit documentation - Test Attribute NUnit documentation - Category Attribute

我想要实现的是这样的:

public class UnitTestAttribute : TestAttribute, CategoryAttribute, ITestAction
{
    public UnitTestAttribute() : base("UnitTest")
    public void BeforeTest(ITest test) { /*some logic*/ }
    public void AfterTest(ITest test) { /*some logic*/ }
    public ActionTargets Targets => ActionTargets.Test;
}

不幸的是,这将不起作用,因为您不能为单个 class 设置 2 个碱基 class。 我想要实现的目标是最大限度地减少我必须编写的代码量,以便将某些测试标记为(在本例中)单元测试,同时能够根据测试的类别过滤测试。所以我现在的代码

[Test, UnitTest]
public void SomeTest() { /*doing some stuff*/ }

将更改为

[UnitTest]
public void SomeTest() { /*doing some stuff*/ }

而且我仍然可以运行 使用以下命令进行测试

  nunit3-console mytest.dll --where "cat == UnitTest"

而且 VS 测试资源管理器也会找到类别等

由于 CategoryAttribute 除了在测试中设置 属性 之外什么都不做,我建议您继承自 TestAttribute 并自己实现类别行为。

您将必须实现 IApplyToTest 接口。在对 IApplyToTest 的调用中,您应该将测试的类别 属性 添加(而不是设置)到您想要的值。这很重要,因为您的测试理论上可以有额外的类别注释。

有关详细信息,请参阅 CategoryAttributePropertyAttribute 的代码。 PropertyAttribute 实际上完成了大部分工作。使用您在 PropertyNames.cs

中找到的类别常量值