Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xunit test Fact multiple times

Tags:

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?

like image 251
rjlopes Avatar asked Aug 07 '15 09:08

rjlopes


People also ask

How do I run a parallel test in xUnit?

Set to true to run the test assemblies in parallel against one other; set to false to run them sequentially. The default value is false . Set to true to run the test collections in parallel against one other; set to false to run them sequentially. The default value is true .

Does xUnit create a new class for each test?

xUnit.net creates a new instance of the test class for every test that is run, so any code which is placed into the constructor of the test class will be run for every single test.

What does Fact mean in xUnit?

Facts are tests which are always true. They test invariant conditions. Theories are tests which are only true for a particular set of data.


1 Answers

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() {     ... } 
like image 171
Marcio Rinaldi Avatar answered Sep 17 '22 09:09

Marcio Rinaldi