Home > Net >  DynamicData not working as expected when using an ImmutableList
DynamicData not working as expected when using an ImmutableList

Time:11-06

Consider the following code:

public static IEnumerable<object[]> TestData
{
    get
    {
        yield return new object[]
        {
            "hello",
            ImmutableList<string>.Empty.AddRange(
                new List<string>()
                {
                    "one",
                    "two"
                }
            )
        };
    }
}

[TestMethod]
[DynamicData(nameof(TestData))]
public void Sandbox(string myString, ImmutableList<string> myList)
{
    var sameListInstantiatedHere = ImmutableList<string>.Empty.AddRange(
        new List<string>()
        {
            "one",
            "two"
        }
    );

    sameListInstantiatedHere.Count.Should().Be(2);

    myString.Should().Be("hello");
    myList.Count.Should().Be(2);
}

I get this error:

Expected myList.Count to be 2, but found 0 (difference of -2).

I really can't figure out why myList has only zero items. Note how I even use the same code to instantiate it in my Sandbox method and how sameListInstantiatedHere.Count.Should().Be(2); passes the test, while myList.Count.Should().Be(2); does not.

Why is that? What am I doing wrong?

CodePudding user response:

Very unexpected behaviour indeed which can be fixed by applying this attribute:

[assembly: TestDataSourceDiscovery(TestDataSourceDiscoveryOption.DuringExecution)]

It seems that this behaviour is caused by MSTest discovery mechanism change introduced in 2.2.6 which by default (without the above attribute) requires the test case data to be serialisable which seems to be the culprit here (note: it does work as expected with List<> but not with ImmutableList<>).

Yet another way to fix it is to switch to xUnit which does work as expected out of the box:

public class UnitTest
{
    public static IEnumerable<object[]> TestData
    {
        get
        {
            yield return new object[]
            {
                "hello",
                ImmutableList.Create("one", "two")
            };
        }
    }    

    [Theory]
    [MemberData(nameof(TestData))]
    public void Sandbox(string myString, ImmutableList<string> myList)
    {
        myString.Should().Be("hello");
        myList.Count.Should().Be(2);
    }
}
  • Related