Is there a better way to pass dynamic inputs in-line to a DataTestMethod? I.e. How to programmatically create test inputs for a data-driven test

rrreee picture rrreee · Jun 27, 2017 · Viewed 9.5k times · Source

I've been looking for this for years and years, and I think I've finally found a real way in "MSTest V2" (meaning the one that comes with .netcore, and is only really handled correctly in Visual Studio 2017). See my answer for my solution.

The problem this solves for me is that my input data is not easily serialized, but I have logic that needs to be tested with many of these inputs. There are lots of reasons why it's better to do it this way, but that was the show-stopper for me; I was forced to have one giant unit test with a for loop going through my inputs. Until now.

Answer

ovolo picture ovolo · Dec 13, 2017

You can now use the DynamicDataAttribute:

[DynamicData(nameof("TestMethodInput"))]
[DataTestMethod]
public void TestMethod(List<string> list)
{
    Assert.AreEqual(2, list.Count);
}

public static IEnumerable<object[]> TestMethodInput
{
    get
    {
        return new[]
        {
            new object[] { new List<string> { "one" } },
            new object[] { new List<string> { "one", "two" } },
            new object[] { new List<string> { "one", "two", "three" } }
        };
    }
}

There is a good short into at https://dev.to/frannsoft/mstest-v2---new-old-kid-on-the-block

There is more gory detail at https://blogs.msdn.microsoft.com/devops/2017/07/18/extending-mstest-v2/