Testfx: Need clean way to share data between parameterized tests

Created on 28 Apr 2017  路  4Comments  路  Source: microsoft/testfx

MSTest v2 needs a clean way to share test-data between tests. It should support objects.

Current approaches fall short:

  • DataRow can't be shared and doesn't support objects (just compile-time values).
  • DataSource doesn't support objects, and requires a database/csv.
  • Looping through an array/collection lumps the cases into a single test, making test results less readable.

Suggest adding the equivalent of NUnit's TestCaseSource, which takes the name of a field, property, or method that returns an IEnumerable (which can handle objects):

```c#
static object[] DivideCases =
{
new object[] { 12, 3, 4 },
new object[] { 12, 2, 6 },
new object[] { 12, 4, 3 }
};

[Test, TestCaseSource("DivideCases")]
public void DivideTest(int n, int d, int q)
{
Assert.AreEqual( q, n / d );
}
```

enhancement

All 4 comments

Absolutely. Thanks for filing this @JVimes . This should also help drive a structure around #141.

This is being discussed in: Microsoft/testfx-docs#12

This has been addressed in 1.2.0-beta release of the Framework/Adapter pair.

Thanks! For others who find this, here's how to try it out:

Make sure you have MSTest v1.2.0 or later. At time of writing it's in beta, so need to install yourself using NuGet's "Include prerelease" checkbox:

image

Then, add a static, object[][] property to your test class. Fill in data. Add[DynamicData("ThePropertyName")] to your method, and make sure it has the right number/type of parameters:

```C#
static object[] Data
{
get => new[]
{
new object[] {1, 2, 3},
new object[] {4, 5, 6}
};
}

[TestMethod]
[DynamicData("Data")]
public void Test1(int a, int b, int c)
{
Assert.AreEqual(1, a % 3);
Assert.AreEqual(2, b % 3);
Assert.AreEqual(0, c % 3);
}
```

You can alternatively use a method that returns an IEnumerablethis doc.

Was this page helpful?
0 / 5 - 0 ratings