Home > Backend Development > C++ > How Can I Pass Complex Parameters to Xunit's [Theory] Tests?

How Can I Pass Complex Parameters to Xunit's [Theory] Tests?

Susan Sarandon
Release: 2024-12-30 05:59:09
Original
535 people have browsed it

How Can I Pass Complex Parameters to Xunit's [Theory] Tests?

Passing Complex Parameters to [Theory]

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.

MemberData Attribute

XUnit offers the MemberData attribute, which allows you to return an IEnumerable property. Each object[] will be unpacked into the parameters of your [Theory] method.

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

ClassData Attribute

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

MemberData overload for Static Members

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

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!

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