我有一个用例,我需要指定要运行的测试类列表。
每个测试类有 x 次测试。我需要制作仅运行指定测试类的自定义测试套件。
有办法做到这一点吗?它们还会显示在测试运行程序中吗?
是的,在 NUnit 中,您可以创建自定义测试套件并指定要包含哪些测试类。您可以使用 TestCaseSource 属性或创建自定义测试套件类来实现此目的。这两种方法都允许您仅运行指定的测试类,并且结果仍应显示在测试运行器中。
这是使用 TestCaseSource 属性的示例:
using NUnit.Framework;
using System;
using System.Collections.Generic;
public class TestClass1
{
[Test]
public void TestMethod1()
{
Assert.Pass();
}
}
public class TestClass2
{
[Test]
public void TestMethod2()
{
Assert.Pass();
}
}
public class CustomTestSuite
{
[TestCaseSource(nameof(TestClassesToRun))]
public void CustomTest(string testClassName)
{
Type testClassType = Type.GetType(testClassName);
if (testClassType != null)
{
NUnit.Framework.TestSuite suite = new NUnit.Framework.TestSuite(testClassType);
suite.Run(new NUnit.Framework.TestResult());
}
else
{
Assert.Fail($"Test class '{testClassName}' not found.");
}
}
private static IEnumerable<string> TestClassesToRun()
{
// Specify the test classes to include in the custom test suite
yield return typeof(TestClass1).FullName;
yield return typeof(TestClass2).FullName;
// Add more test classes here as needed
}
}
在此示例中,CustomTestSuite 是一个自定义测试套件类,其中包含 CustomTest 方法,该方法从指定的测试类运行测试。 TestClassesToRun 方法指定要包含在自定义测试套件中的测试类。
当您使用 NUnit 运行 CustomTestSuite 类时,只会执行指定测试类中的测试,并且结果仍应显示在测试运行器中。