Xunit test fact several times

I have several methods that rely on random computing to make a suggestion, and I need to run Fact a few times to make sure everything is in order.

I could include a for loop in the fact that I want to test, but since there are several tests in which I want to do this, I was looking for a cleaner approach, something like this Repeat attribute in junit: http: // www. codeaffine.com/2013/04/10/ JUNit-tests-times-without-loops /

Can I easily implement something like this in xunit?

+12
source share
2 answers

You will need to create a new DataAttribute to tell xunit to run the same test several times.

Here is an example, 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, you just need to change Fact to Theory and use Repeat as follows:

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

There was the same requirement, but the accepted answer code did not repeat the tests, so I adapted it to:

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

Although Enumerable.Repeat was used in the previous example, the test was run only 1 time, since xUnit does not repeat the test. They probably changed something a while ago. Moving on to the foreach we can repeat each test, but we also provide an “iteration number”. When using it in a test function, you must add a parameter to your test function and style it as Theory as shown here:

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

This works for xUnit 2.4.0.

I created the NuGet package to use in case anyone would be interested.

+2
source

All Articles