如何运行 NUnit 测试?

now*_*wox 0 c# nunit

我想要一个独立的项目来测试通过 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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Ser*_*hyk 5

我知道两种可能的解决方案来实现你想要的。NUnit 团队在 nuget 上发布了NUnit 引擎NUnit 控制台

使用 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
    {
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

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

它不适合只想运行测试的用户直接使用。

使用标准的 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
    {
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

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