Nunit-C#:通过编码运行特定的测试

时间:2013-04-25 13:25:29

标签: c# nunit

我正在使用Selenium和C#进行自动化,我想通过代码调用NUnit,如下所示:

CoreExtensions.Host.InitializeService();
TestPackage testPackage = new TestPackage(@"D:\Automation\bin\Debug\Test.dll");
RemoteTestRunner remoteTestRunner = new RemoteTestRunner();
remoteTestRunner.Load(testPackage);
//TestFilter filter = new NameFilter(new TestName() { Name = "Test1" });
TestResult testResult = remoteTestRunner.Run(
    new NullListener(),
    TestFilter.Empty,
    false,
    LoggingThreshold.Off
); 

我可以使用类别过滤器运行测试,如下所示

remoteTestRunner.Run(
    new NullListener(),
    new CategoryFilter("MyCat"),
    false,
    LoggingThreshold.Off
);

但我想执行特定的测试。如何设置套件过滤器?我尝试了以下方法,但它不起作用:

TestFilter filter = new NameFilter(new TestName() { Name = "Test1" }); 
TestResult testResult = remoteTestRunner.Run(
    new NullListener(),
    filter,
    false,
    LoggingThreshold.Off
);

如何运行特定测试以及如何通过代码传递参数?

2 个答案:

答案 0 :(得分:6)

此示例代码应该让您了解如何开始在测试中循环并选择要运行的测试。我已经使用了几个数组索引0,你应该在其中循环。

它的主要部分是你必须先加载测试才能开始尝试单独运行它们,因为测试需要有一个唯一的TestId,只有在加载后才能设置它。以下代码在测试框架中的第一个testfixture中运行并运行第一个测试。它还会扫描所有测试名称,以便根据某些标准显示或运行

CoreExtensions.Host.InitializeService();
TestSuiteBuilder builder = new TestSuiteBuilder();
TestPackage testPackage = new TestPackage(@"path.to.dll");
RemoteTestRunner remoteTestRunner = new RemoteTestRunner();
remoteTestRunner.Load(testPackage);
TestSuite suite = builder.Build(testPackage);
TestSuite test = suite.Tests[0] as TestSuite;
var numberOfTests = ((TestFixture)test.Tests[0]).TestCount;

foreach (TestMethod t in ((TestFixture)test.Tests[0]).Tests)
{
    Console.WriteLine(t.TestName.Name);
}

TestName testName = ((TestMethod)((TestFixture)test.Tests[0]).Tests[0]).TestName;
TestFilter filter = new NameFilter(testName);
TestResult result = test.Run(new NullListener(), filter);
ResultSummarizer summ = new ResultSummarizer(result);
Assert.AreEqual(1, summ.ResultCount);

答案 1 :(得分:0)

这是我的工作代码......

    SimpleNameFilter filter = new SimpleNameFilter()

    foreach (DataRow DR in DT.Rows)
    {
    string Test = "FullNameOftheTest";
    filter.Add(Test); 
    }

  CoreExtensions.Host.InitializeService();
  TestPackage testPackage = new TestPackage(@"D:\Test\Test.dll");
  RemoteTestRunner remoteTestRunner = new RemoteTestRunner();
  remoteTestRunner.Load(testPackage);
  TestResult result = remoteTestRunner.Run(new NullListener(), filter, true,          LoggingThreshold.All);
  ResultSummarizer summaryResults = new ResultSummarizer(result);

感谢大家的支持, 基肖尔马布。