简体   繁体   中英

Using xunit to generate multiple test cases with integer range

Is there a way to automatically generate multiple test cases in xUnit? Or am I doomed to specify each possible input as an InlineData ?

In the example below, in NCrunch or the VS test runner it looks like a random number is passed in to the test. So everytime you run the test, there is a chance it will pass, although it should fail.

In NUnit the Range attribute actually generates multiple permutations of the test case as per https://github.com/nunit/docs/wiki/Range-Attribute

public bool RangeTest(int input)
{

    if (input > 10)
    {
        return false;
    }

    return true;
}

[Theory]
[AutoMockData]
public void RangeTestCase([Range(0, 11)] int test)
{
    var result = RangeTest(test);      

    Assert.True(result);
}

Here is a good explanaition how to make the test: https://andrewlock.net/creating-parameterised-tests-in-xunit-with-inlinedata-classdata-and-memberdata/ In your case you must create a dedicated data class wich will return the date for the test;

public class GetTestData : IEnumerable<Int32>
{
 public IEnumerator<Int32> GetEnumerator()
 {
    yield return 1;
    yield return 2;
    yield return 3;
    yield return 4;

   IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
 }
}

and the usage of the class will be:

[Theory]
[ClassData(typeof(GetTestData ))]
public bool RangeTest(int input)

But for test is a good idea to test only the edge cases. You must avoid the randomness in the tests.

AutoFixture doesn't provide such a feature out of the box. There is a way to do that by creation of a custom DataAttribute , but as it has been highlighted by the answer around you shouldn't do that. It sounds quite oxymoronic, but you should avoid randomness when using AutoFixture. You still should check the boundary values using multiple instances of eg InlineAuto[Moq]Data attribute, so it fails/passes predictably and for each time.

As for the generated values, they should be used only when it does't cause randomness. For example, it might be:

  • places where input doesn't matter for the current test;
  • scenarios when you do identity check - you verify that same value appears as a result; in this case you are not interested in what exactly the value is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM