xunit test事实多次

问题描述 投票:14回答:2

我有一些方法依赖于一些随机计算来提出建议,我需要多次运行Fact以确保没问题。

我可以在我要测试的事实中包含一个for循环,但因为有几个测试我想要这样做,我查找了一个更干净的方法,类似于junit中的重复属性:http://www.codeaffine.com/2013/04/10/running-junit-tests-repeatedly-without-loops/

我可以在xunit中轻松实现这样的功能吗?

c# random xunit
2个回答
27
投票

你必须创建一个新的DataAttribute来告诉xunit多次运行相同的测试。

以下是一个遵循junit相同概念的示例:

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

有了这个代码,你只需要将你的Fact更改为Theory并像这样使用Repeat

[Theory]
[Repeat(10)]
public void MyTest()
{
    ...
}

3
投票

有相同的要求,但接受的答案代码没有重复测试,所以我已经适应:

public sealed class RepeatAttribute : Xunit.Sdk.DataAttribute
{
    private readonly int count;

    public RepeatAttribute(int count)
    {
        if (count < 1)
        {
            throw new System.ArgumentOutOfRangeException(
                paramName: nameof(count),
                message: "Repeat count must be greater than 0."
                );
        }
        this.count = count;
    }

    public override System.Collections.Generic.IEnumerable<object[]> GetData(System.Reflection.MethodInfo testMethod)
    {
        foreach (var iterationNumber in Enumerable.Range(start: 1, count: this.count))
        {
            yield return new object[] { iterationNumber };
        }
    }
}

虽然在上一个例子中使用了Enumerable.Repeat,但它只会运行测试1次,不知何时xUnit没有重复测试。可能是他们前一段时间发生过变化的事情。通过更改为foreach循环,我们可以重复每个测试,但我们也提供“迭代次数”。在测试函数上使用它时,您必须向测试函数添加一个参数并将其装饰为Theory,如下所示:

[Theory(DisplayName = "It should work")]
[Repeat(10)]
public void It_should_work(int iterationNumber)
{
...
}

这适用于xUnit 2.4.0。

我已经创建了一个NuGet package来使用它以防任何人感兴趣。

© www.soinside.com 2019 - 2024. All rights reserved.