xunit test Fact multiple times

rjlopes picture rjlopes · Aug 7, 2015 · Viewed 8.8k times · Source

I have some methods that rely on some random calculations to make a suggestion and I need to run the Fact several times to make sure is ok.

I could include a for loop inside the fact i want to test but because there are several test where I want to do this I was lookup for a cleaner approach, something like this Repeat attribute in junit: http://www.codeaffine.com/2013/04/10/running-junit-tests-repeatedly-without-loops/

Can I easily implement something like this in xunit?

Answer

Marcio Rinaldi picture Marcio Rinaldi · Aug 7, 2015

You'll have to create a new DataAttribute to tell xunit to run the same test multiple times.

Here's is a sample following the same idea of 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);
    }
}

With this code in place, you just need to change your Fact to Theory and use the Repeat like this:

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