简体   繁体   English

如何从C#代码运行NUnit测试

[英]How to Run NUnit Tests from C# Code

I'm trying to write a simple method that receives a file and runs it using NUnit. 我正在尝试编写一个接收文件并使用NUnit运行它的简单方法。 The code I managed to build using NUnit's source does not work: 我使用NUnit的源代码构建的代码不起作用:

if(openFileDialog1.ShowDialog() != DialogResult.OK)
{
    return;
}

var builder = new TestSuiteBuilder();
var testPackage = new TestPackage(openFileDialog1.FileName);
var directoryName = Path.GetDirectoryName(openFileDialog1.FileName);
testPackage.BasePath = directoryName;
var suite = builder.Build(testPackage);

TestResult result = suite.Run(new NullListener(), TestFilter.Empty);

The problem is that I keep getting an exception thrown by builder.Build stating that the assembly was not found. 问题是我不断得到builder.Build抛出的异常,说明找不到程序集。

What am I missing? 我错过了什么? Is there some other way to run the test from the code (without using Process.Start)? 是否有其他方法从代码运行测试(不使用Process.Start)?

Adding the following line at the beginning, sets up the NUnit framework and might help you: 在开头添加以下行,设置NUnit框架并可能对您有所帮助:

CoreExtensions.Host.InitializeService();

Another "easier" way to execute NUnit tests programmatically would be: 以编程方式执行NUnit测试的另一种“更简单”的方法是:

TestPackage testPackage = new TestPackage(@"C:\YourProject.Tests.dll");
RemoteTestRunner remoteTestRunner = new RemoteTestRunner();
remoteTestRunner.Load(testPackage);
TestResult testResult = remoteTestRunner.Run(new NullListener());

You need to reference the following assemblies: 您需要引用以下程序集:

  • nunit.core.dll
  • nunit.core.interfaces.dll

And of course, the nunit.framework.dll must be in the folder with your test assembly ;) 当然, nunit.framework.dll必须位于测试程序集的文件夹中;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM