In a sense this is equivalent to TheoryData
, but applied at the level of test class rather than at the level of the method. Is this possible within current XUnit framework? If yes, then how exactly?
Fact vs Theory Tests The primary difference between fact and theory tests in xUnit is whether the test has any parameters. Theory tests take multiple different inputs and hold true for a particular set of data, whereas a Fact is always true, and tests invariant conditions.
This method is decorated with the Fact attribute, which tells xUnit that this is a test.
You can use the class fixture feature of xUnit.net to share a single object instance among all tests in a test class. We already know that xUnit.net creates a new instance of the test class for every test.
You can do it with a ClassData as mentioned here
You create some kind of Generator class like below and use the ClassData fixture with Theory.
public class TestDataGenerator : IEnumerable<object[]>
{
private readonly List<object[]> _data = new List<object[]>
{
new object[] {5, 1, 3, 9},
new object[] {7, 1, 5, 3}
};
public IEnumerator<object[]> GetEnumerator() => _data.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
public class ParameterizedTests
{
public bool IsOddNumber(int number)
{
return number % 2 != 0;
}
[Theory]
[ClassData(typeof(TestDataGenerator))]
public void AllNumbers_AreOdd_WithClassData(int a, int b, int c, int d)
{
Assert.True(IsOddNumber(a));
Assert.True(IsOddNumber(b));
Assert.True(IsOddNumber(c));
Assert.True(IsOddNumber(d));
}
}
You can use IClassFixture. Create a customized TFixture to return data to your test class constructor.
namespace Xunit
{
public interface IClassFixture<TFixture> where TFixture : class
{
}
}
And your method should inherit the customized fixture
public class ParameterizedTests: IClassFixture<TFixture>
{
public ParameterizedTests(TFixture fixture)
{
}
public bool IsOddNumber(int number)
{
return number % 2 != 0;
}
[Theory]
[ClassData(typeof(TestDataGenerator))]
public void AllNumbers_AreOdd_WithClassData(int a, int b, int c, int d)
{
Assert.True(IsOddNumber(a));
Assert.True(IsOddNumber(b));
Assert.True(IsOddNumber(c));
Assert.True(IsOddNumber(d));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With