简体   繁体   English

有没有办法多次重复 nUnit TestFixture?

[英]Is there a way to repeat a nUnit TestFixture multiple times?

Is there a way to run a nunit TestFixture once for each item in a list?有没有办法为列表中的每个项目运行一次 nunit TestFixture? Let's say I have a setup something like the following:假设我有一个类似以下的设置:

Public Class TestData
{
Public String Parameter1{get;}
Public String Parameter2{get;}
Public String Parameter3{Get;}
}

What I would like to do is create a list of TestData objects:我想做的是创建一个 TestData 对象列表:

List<TestData> inputs = new List<TestData>(){};

And then using nunit 3, run a TestFixture and all Tests housed within it against each item in the list.然后使用 nunit 3,针对列表中的每个项目运行一个 TestFixture 和其中包含的所有测试。

The TestFixtureAttribute may take a list of arguments, similar to the TestCaseAttribute . TestFixtureAttribute可以采用 arguments 的列表,类似于TestCaseAttribute The values provided are used as arguments to the constructor of the test class.提供的值用作测试 class 的构造函数的 arguments。 The usual process is to save the constructor arguments in a member variable.通常的过程是将构造函数 arguments 保存在成员变量中。 For example:例如:

[TestFixture(123, "John")]
[TestFixture(456, "Mary")]
[TestFixture(789, "Fred")]
public class MyTest
{
    private int _num;
    private string _name;

    public MyTest(int num, string name)
    {
        _num = num;
        _name = name;
    }

    ...
}

The fixture will be created and executed three times, once for each set of arguments.夹具将被创建和执行三次,每组 arguments 一次。 You may use the saved values in your tests, which may be simple tests or parameterized tests.您可以在测试中使用保存的值,这可能是简单测试或参数化测试。

As with [TestCase] , you are limited to constant arguments of the types permitted by the C# languge.[TestCase]一样,您只能使用 C# 语言所允许的类型的常量 arguments。

If you don't like that limitation and/or have a lot of test cases and prefer to consolidate the data, you can replace all the [TestFixture] entries by a single [TestFixtureSource] , like this...如果您不喜欢这种限制和/或有很多测试用例并且更喜欢合并数据,则可以将所有[TestFixture]条目替换为单个[TestFixtureSource] ,如下所示...

[TestFixtureSource(nameof(MyTestData))]
public class MyTest
{
    private int _num;
    private string _name;

    public MyTest(int num, string name)
    {
        _num = num;
        _name = name;
    }

    ...

    static IEnumerable<TestFixtureData> MyTestData()
    {
        yield return new TestFixtureData(123, "John");
        yield return new TestFixtureData(456, "Mary");
        yield return new TestFixtureData(789, "Fred");
    }
}

This attribute is a bit more complicated than [TestCase] so be sure to read the documentation .这个属性比[TestCase]稍微复杂一些,所以一定要阅读文档 In particular, check out "Form 2" if you want to share the same data among multiple fixture classes.特别是,如果您想在多个夹具类之间共享相同的数据,请查看“表格 2”。

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

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