This SO answer显示的代码应该导致Xunit理论测试在应用此方法属性的情况下多次运行:
[Theory]
[Repeat(3)]
public void MyTest()
{
// test code here
}
Repeat()
属性定义为:
public class RepeatAttribute : DataAttribute
{
private readonly int _count;
public RepeatAttribute(int count)
{
if (count < 1)
{
throw new ArgumentOutOfRangeException(nameof(count), "Repeat count must be greater than 0.");
}
_count = count;
}
public override IEnumerable<object[]> GetData(MethodInfo testMethod)
{
return Enumerable.Repeat(new object[0], _count);
}
}
这种情况的用例是让Xunit多次运行测试理论,直到数据耗尽为止。例如,当要运行的测试由外部绘制的数据而不是特定编码的方法数定义时。
不幸的是,这产生的错误是:
[xUnit.net 00:00:00.55] Basic: Skipping test case with duplicate ID '071bf13109c976bcd6c61a7afa145a7a1cdb8e0a' ('Basic.Tests.MyTest()' and 'Basic.Tests.MyTest()')
[xUnit.net 00:00:00.55] Basic: Skipping test case with duplicate ID '071bf13109c976bcd6c61a7afa145a7a1cdb8e0a' ('Basic.Tests.MyTest()' and 'Basic.Tests.MyTest()')
有没有解决的办法?
我已经尝试重写Skip
属性,但要么我找不到合适的值才能返回,或者它没有达到预期的效果。
[编辑]为了回应@peterszabo接受的答案,我的代码现在看起来像这样:
public class RepeatAttribute : DataAttribute
{
private readonly int _count;
public RepeatAttribute(int count)
{
if (count < 1)
{
throw new ArgumentOutOfRangeException(nameof(count), "Repeat count must be greater than 0.");
}
_count = count;
}
public override IEnumerable<object[]> GetData(MethodInfo testMethod)
{
var list = new List<object[]>();
for (var i=1; i<=10; i++)
list.Add(new object[] {i});
return list as IEnumerable<object[]>;
}
}
这是每个object[]
中list.Add()
的内容将会改变。
测试输入没有差异。你的属性返回一个空的对象数组,你的理论没有参数,所以你基本上试图一遍又一遍地运行相同的测试。所以它在第一次执行后被跳过。
如果您的测试输入数据是
由外部绘制的数据定义
那么你可能想要尝试的是让你的DataAttribute
读取外部数据源并从中获得结果。然后,您可以将此数据作为[Theory]
方法的参数接收。
您可以在Andrew Lock的博客here上看到使用JSON文件作为测试理论的外部数据源的示例。