如何 运行 进行 NUnit 测试?

How to run a NUnit test?

我想要一个独立的项目来测试通过 USB 连接的远程系统的某些功能。

所以我想在我的应用程序中使用 NUnit 的所有功能。

我目前写的是:

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

如何 运行 我的测试套件以及如何获得测试报告?

我知道两种可能的解决方案来实现你想要的。 NUnit 团队在 nuget 上发布了 NUnit Engine and NUnit Console

使用 NUnit 引擎

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
    {
        // ...
    }
}

从 nuget 安装 Nuget Engine package 以便 运行 这个例子。结果将在 result 变量中。给所有想使用这个包的人一个警告:

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

使用标准的 NUnit 控制台应用程序

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
    {
        // ...
    }
}

从 nuget 安装 NUnit Engine and NUnit Console 包。在您的项目中添加对 nunit3-console.exe 的引用。结果将保存在 TestResult.xml 文件中。我不喜欢这种方法,因为您可以使用一个简单的批处理文件实现相同的目的。