Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What`s .Net core alternative of DataSource attribute for mstest?

From the below, got to know that DataSource attribute is no more supported on .net core projects of MSTest. So what`s the alternative to this?

Link: https://learn.microsoft.com/en-us/visualstudio/test/how-to-create-a-data-driven-unit-test?view=vs-2019

Info: .NET Core does not support the DataSource attribute. If you try to access test data in this way in a .NET Core or UWP unit test project, you'll see an error similar to "'TestContext' does not contain a definition for 'DataRow' and no accessible extension method 'DataRow' accepting a first argument of type 'TestContext' could be found (are you missing a using directive or an assembly reference?)".

like image 657
DeSon Avatar asked Oct 14 '25 15:10

DeSon


1 Answers

September 7th, 2020 - No workaround

There is an open issue issue-233 about this and no comments on when it can be fixed. There are some work-arounds:

DynamicDateAttribute (CSV Example)

private static string[] SplitCsv(string input)
{
    var csvSplit = new Regex("(?:^|,)(\"(?:[^\"]+|\"\")*\"|[^,]*)", RegexOptions.Compiled);
    var list = new List<string>();
    foreach (Match match in csvSplit.Matches(input))
    {
        string value = match.Value;
        if (value.Length == 0)
        {
            list.Add(string.Empty);
        }

        list.Add(value.TrimStart(','));
    }
    return list.ToArray();
}

private static IEnumerable<string[]> GetData()
{
    IEnumerable<string> rows = System.IO.File.ReadAllLines(@"Resources\NameAddressCityStateZip.csv").Skip(1);
    foreach (string row in rows)
    {
        yield return SplitCsv(row);
    }
}

[TestMethod]
[DynamicData(nameof(GetData), DynamicDataSourceType.Method)]
//x [DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", @"Resources\NameAddressCityStateZip.csv", "NameAddressCityStateZip#csv", DataAccessMethod.Sequential)]
public void TestMethod1(string input, string expected)
{
    // Arrange
    //x string input = _testContext.Properties["Data"].ToString(); //x _testContext.DataRow["Data"].ToString();
    //x string expected = _testContext.Properties["Expected"].ToString(); //x _testContext.DataRow["Expected"].ToString();
    var parser = _serviceProvider.GetService<Parser>();

    // Act
    string actual = parser.MultiParser(input, ModeType.NameAddressCityStateZipCountry).ToString();

    // Assert
    Assert.AreEqual(expected, actual);
}

but there are drawbacks to it.

Port it yourself code

As exibited in the comment here

Wait for the implementation

like image 171
Athanasios Kataras Avatar answered Oct 17 '25 04:10

Athanasios Kataras



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!