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

如何在OneTimeSetup方法中读取待执行的NUnit测试列表?

在NUnit的OneTimeSetup中获取待执行的测试列表

你可以借助NUnit的TestContext和ITest接口实现需求,直接在OneTimeSetUp方法中筛选出即将执行的测试用例名称,具体实现如下:

using NUnit.Framework;
using NUnit.Framework.Interfaces;
using System.Collections.Generic;
using System.Linq;

[TestFixture]
public class MyTestClass
{
    [OneTimeSetUp]
    public void OneTimeSetUp()
    {
        // 获取当前测试类的测试节点
        ITest testClass = TestContext.CurrentContext.Test;
        
        // 筛选出实际会执行的测试用例(排除忽略、不可运行的测试)
        List<string> executingTests = testClass.Tests
            .Where(t => t.RunState == RunState.Runnable || t.RunState == RunState.Explicit)
            .Select(t => t.Name)
            .ToList();
        
        // 执行你的项目特定操作,比如打印待执行测试列表
        foreach (string testName in executingTests)
        {
            TestContext.Progress.WriteLine($"待执行测试:{testName}");
        }
    }

    [Test]
    public void TestCase1() { /* 测试逻辑 */ }

    [Test]
    public void TestCase2() { /* 测试逻辑 */ }

    [Test, Ignore("暂不执行")]
    public void TestCase3() { /* 测试逻辑 */ }

    [Test]
    public void TestCase4() { /* 测试逻辑 */ }

    [Test]
    public void TestCase5() { /* 测试逻辑 */ }
}

关键说明

  • TestContext.CurrentContext.Test:获取当前测试类的ITest实例,其Tests属性包含类下所有测试用例节点。
  • RunState筛选:通过RunState.Runnable(正常可执行)和RunState.Explicit(主动指定才会执行)过滤出实际会运行的测试,自动排除RunState.Ignored(标记忽略)和RunState.NotRunnable(不可运行)的测试。
  • 适配指定运行场景:如果通过测试运行器、命令行指定了仅执行部分测试(比如只运行TestCase1和TestCase2),NUnit会提前更新对应测试节点的RunState,该方法依然能准确获取到最终要执行的测试列表。

内容的提问来源于stack exchange,提问作者Leo Danny

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 03:32:37