Home > Backend Development > C++ > How Can I Pass Complex Parameters, Like Lists of Custom Classes, to XUnit Theories?

How Can I Pass Complex Parameters, Like Lists of Custom Classes, to XUnit Theories?

Patricia Arquette
Release: 2025-01-02 14:10:38
Original
298 people have browsed it

How Can I Pass Complex Parameters, Like Lists of Custom Classes, to XUnit Theories?

Passing Complex Parameters to Theories

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, each item in the collection can be unpacked as a parameter for a single theory method call.

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" } } },
};
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template