Problem:
XUnit allows creating parameterized tests using InlineData attributes. However, challenges arise when dealing with complex parameters, such as lists of custom classes.
Answer:
XUnit provides various Data attributes, including MemberData. By implementing a property that returns IEnumerable
MemberData Example:
public class MyClass { public string Name { get; set; } } public static void WriteReportsToMemoryStream( IEnumerable<MyClass> listReport, MemoryStream ms, StreamWriter writer) { ... } [Theory, MemberData(nameof(Data))] public void WriteReports(IEnumerable<MyClass> listReport) { using (var ms = new MemoryStream()) { using (var writer = new StreamWriter(ms)) { WriteReportsToMemoryStream(listReport, ms, writer); // ... } } } public static IEnumerable<object[]> Data => new[] { new object[] { new[] { new MyClass { Name = "Item1" } } }, new object[] { new[] { new MyClass { Name = "Item2" } } }, };
The Data property generates an enumerable of object arrays, where each array corresponds to a set of parameters for the WriteReports method.
The above is the detailed content of How Can I Pass Complex Parameters, Like Lists of Custom Classes, to XUnit Theories?. For more information, please follow other related articles on the PHP Chinese website!