如何在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
相关产品推荐
相关产品推荐

