You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多类别TestFixtures中如何让特定测试仅在指定类别下可见

解决方案

针对NUnit框架,要实现在测试发现阶段就让Test2仅在Category="B"下可见,可通过[IgnoreOnCategories]特性实现,具体代码如下:

[TestFixture(Category="A")]
[TestFixture(Category="B")]
public class YourTestClass
{
    [Test]
    void Test1() {}

    [Test]
    [IgnoreOnCategories("A")]
    void Test2() {}
}

原理说明

  • [IgnoreOnCategories("A")]是NUnit 3及以上版本提供的特性,作用是在测试发现阶段,当所在的TestFixture属于指定类别时,直接忽略该测试方法,不会生成对应的测试条目。
  • 当TestFixture为Category="A"时,Test2会被该特性过滤,不生成Test2-A的条目;而Category="B"时,该特性不生效,Test2-B正常显示。
  • 最终测试列表只会出现Test1-A、Test1-B、Test2-B三个条目,执行完成后统计为"3/3通过",完全符合需求,且无需运行时忽略逻辑。

另一种可选方案是拆分测试类的TestFixture,将仅属于B类别的测试单独放在对应TestFixture中,代码示例:

[TestFixture(Category="A")]
public class YourTestClassA
{
    [Test]
    void Test1() {}
}

[TestFixture(Category="B")]
public class YourTestClassB
{
    [Test]
    void Test1() {}

    [Test]
    void Test2() {}
}

这种方案通过物理拆分实现需求,优点是逻辑清晰,适合测试方法较多的场景;缺点是需要维护多个测试类。

内容的提问来源于stack exchange,提问作者David V. Corbin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 04:25:04