CodeWeed
CodeWeed

Reputation: 1071

How to test a method with List<List<T> as input parameter in Xunit

I want to test a method with List<List<string>> as parameter. I am using xunit as testing framework.

Here is what I tried.

public static IEnumerable<IEnumerable<string>> CombinationData
{
    get
    {
        return new List<List<string>>
        {
            new List<string>{ "a", "b", "c" }, 
            new List<string>{ "x", "y", "z" }
        };
    }
}

[Theory]
[MemberData(nameof(CombinationData))]
public void CombinationDataTest(List<List<string>> dataStrings)
{
     ...
}

I get the following exception when the run the test.

System.ArgumentException :
Property CombinationData on CodeUnitTests.MainCodeTests yielded an item that is not an object[]
Stack Trace: at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()

How do I make it work ? Is it the right approach ?

Upvotes: 2

Views: 4371

Answers (1)

Fabio
Fabio

Reputation: 32445

Error message is pretty clear. Function provided for MemberData should return IEnumerable<object[]>, where

  • Every item of IEnumerable is collection of parameters for one test case
  • Every object in object[] is parameter expected by test method

Your test method expect List<List<string>> as parameter so you should return instance of List<List<string>> as first item of object[]

private static IEnumerable<object[]> CombinationData()
{
    var testcase = new List<List<string>>
    {
        new List<string>{ "a", "b", "c" }, 
        new List<string>{ "x", "y", "z" }
    };  
    yield return new object[] { testcase };
}

Upvotes: 3

Related Questions