Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Run NUnit Tests from C# Code

Tags:

I'm trying to write a simple method that receives a file and runs it using NUnit. The code I managed to build using NUnit's source does not work:

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.

What am I missing? Is there some other way to run the test from the code (without using Process.Start)?

like image 558
Dror Helper Avatar asked May 13 '10 10:05

Dror Helper


People also ask

How do I run a NUnit test in C#?

Navigate to Tools -> NuGet Package Manager -> Manager NuGet Packages for Solution. Search for NUnit & NUnit Test Adapter in the Browse tab. Click on Install and press OK to confirm the installation. With this installation, the NUnit framework can be used with C#.

How do you use NUnit testing?

Creating the first testThe NUnit test runner contains the program entry point to run your tests. dotnet test starts the test runner using the unit test project you've created. In the unit-testing-using-nunit directory, run dotnet test again.


1 Answers

Adding the following line at the beginning, sets up the NUnit framework and might help you:

CoreExtensions.Host.InitializeService(); 

Another "easier" way to execute NUnit tests programmatically would be:

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 ;)

like image 198
Martin Buberl Avatar answered Dec 06 '22 22:12

Martin Buberl