简体   繁体   中英

How to run a NUnit test?

I would like to have a standalone project that will test some features of a remote system connected through USB.

So I want to use all the power of NUnit inside my application.

I currently wrote this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using NUnit.Framework;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.ReadLine();
        }
    }

    [TestFixture]
    public class MyTest
    {
        [Test]
        public void MyTest()
        {
            int i = 3;
            Assert.AreEqual(3, i);
        }
    }
}

How do I run my test-suite and how do I get a test-report?

I know two possible solutions to achieve what you want. The NUnit team published NUnit Engine and NUnit Console on nuget.

Using the NUnit Engine

using NUnit.Engine;
using NUnit.Framework;
using System.Reflection;
using System.Xml;
using System;

public class Program
{
    static void Main(string[] args)
    {
        // set up the options
        string path = Assembly.GetExecutingAssembly().Location;
        TestPackage package = new TestPackage(path);
        package.AddSetting("WorkDirectory", Environment.CurrentDirectory);

        // prepare the engine
        ITestEngine engine = TestEngineActivator.CreateInstance();
        var _filterService = engine.Services.GetService<ITestFilterService>();
        ITestFilterBuilder builder = _filterService.GetTestFilterBuilder();
        TestFilter emptyFilter = builder.GetFilter();

        using (ITestRunner runner = engine.GetRunner(package))
        {
            // execute the tests            
            XmlNode result = runner.Run(null, emptyFilter);
        }
    }

    [TestFixture]
    public class MyTests
    {
        // ...
    }
}

Install the Nuget Engine package from nuget in order to run this example. The results will be in the result variable. There is a warning for everyone who wants to use this package:

It is not intended for direct use by users who simply want to run tests.

Using the standard NUnit Console Application

using NUnit.Framework;
using System.Reflection;

class Program
{
    static void Main(string[] args)
    {
        string path = Assembly.GetExecutingAssembly().Location;
        NUnit.ConsoleRunner.Program.Main(new[] { path });
    }

    [TestFixture]
    public class MyTests
    {
        // ...
    }
}

Install NUnit Engine and NUnit Console packages from nuget. Add a reference to nunit3-console.exe in your project. The results will saved in the TestResult.xml file. I don't like this approach, because you can achieve the same using a simple batch file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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