Passing simple data types such as strings, integers, and doubles as parameters to [Theory] tests in Xunit is straightforward using attributes like InlineData. However, for more complex parameters, the question arises of how to provide such data.
XUnit offers the MemberData attribute, which allows you to return an IEnumerable
For example:
public class StringTests { [Theory, MemberData(nameof(SplitCountData))] public void SplitCount(string input, int expectedCount) { Assert.Equal(expectedCount, input.Split(' ').Length); } public static IEnumerable<object[]> SplitCountData => new List<object[]> { { "xUnit", 1 }, { "is fun", 2 }, { "to test with", 3 } }; }
Prior to Xunit 2.0, you could use the ClassData attribute to share data generators between tests in different classes.
For example:
public class StringTests { [Theory, ClassData(typeof(IndexOfData))] public void IndexOf(string input, char letter, int expected) { Assert.Equal(expected, input.IndexOf(letter)); } } public class IndexOfData : IEnumerable<object[]> { // ... data and methods }
In Xunit 2.0 and later, MemberData can take a MemberType parameter to specify a static member from another class.
For example:
public class StringTests { [Theory] [MemberData(nameof(IndexOfData.SplitCountData), MemberType = typeof(IndexOfData))] public void SplitCount(string input, int expectedCount) { Assert.Equal(expectedCount, input.Split(' ').Length); } }
Alternatively, you can still use ClassData if you prefer separation between data generators and test methods.
The above is the detailed content of How Can I Pass Complex Parameters to Xunit's [Theory] Tests?. For more information, please follow other related articles on the PHP Chinese website!