简体   繁体   中英

DynamicData - Unable to move the static method to another class (Even Base class)

I'm developing a Dynamic Data Test (c#) as described in https://www.meziantou.net/mstest-v2-data-tests.htm#using-dynamicdata .

By keeping both the Dynamic Data Test and the static method within the same class, then all works fine, but when trying to move the static class to another class (Even Base class), then the test doesn't run and I get an error message:

Message: Value cannot be null. Parameter name: Method GetData

Can you please assist?

When moving the method to another class, I tried to make it as none-static too, but that didn't help.

[TestClass]
public class MathTests
{
    [DataTestMethod]
    [DynamicData(nameof(GetData), DynamicDataSourceType.Method)]
    public void Test_Add_DynamicData_Method(int a, int b, int expected)
    {
        var actual = MathHelper.Add(a, b);
        Assert.AreEqual(expected, actual);
    }

    public static IEnumerable<object[]> GetData()
    {
        yield return new object[] { 1, 1, 2 };
        yield return new object[] { 12, 30, 42 };
        yield return new object[] { 14, 1, 15 };
    }
}

Use the alternate constructor for the attribute that includes the type that contains the target data source

For example

[TestClass]
public class MathTests
{
    [DataTestMethod]
    [DynamicData(nameof(ExternalClass.GetData), typeof(ExternalClass), DynamicDataSourceType.Method)]
    public void Test_Add_DynamicData_Method(int a, int b, int expected)
    {
        var actual = MathHelper.Add(a, b);
        Assert.AreEqual(expected, actual);
    }

}

public class ExternalClass
{
    public static IEnumerable<object[]> GetData()
    {
        yield return new object[] { 1, 1, 2 };
        yield return new object[] { 12, 30, 42 };
        yield return new object[] { 14, 1, 15 };
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM