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 };
}
}
Instance variables can be accessed in non-static methods (i.e. instance methods) Static variables and methods are accessed in non-static contexts by using <class name>.<static variable or method name> (if the visibility modifier allows it) The problem you're running into is that you/your class is trying to mix static and non-static contexts.
You need to call static members against the class, not against an instance of a class. So you need to use: Classes are internal by default. I would recommend you always be explicit about visibility (i.e. always specify internal, public or private ).
In general... Instance variables can be accessed in non-static methods (i.e. instance methods) Static variables and methods are accessed in non-static contexts by using <class name>.<static variable or method name> (if the visibility modifier allows it)
This is where the DynamicData attribute comes in. You specify a test data generator method (or property). This generator method returns a list of test parameter arrays. Each bucket in the list is a different test run. The following shows how to add the DynamicData attribute to a unit test, pointing to a static test method called GetTestData:
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 };
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With