TestFixtureAttribute 可以接受参数列表,类似于TestCaseAttribute。提供的值用作测试类构造函数的参数。通常的过程是将构造函数参数保存在成员变量中。例如:
[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;
}
...
}
fixture 将被创建和执行三次,每组参数一次。您可以在测试中使用保存的值,可以是简单测试或参数化测试。
与 [TestCase] 一样,您只能使用 C# 语言允许的类型的常量参数。
如果您不喜欢这种限制和/或有很多测试用例并希望合并数据,您可以将所有 [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");
}
}
这个属性比[TestCase] 稍微复杂一些,所以一定要阅读documentation。特别是,如果您想在多个夹具类之间共享相同的数据,请查看“表格 2”。