如何将二维数组设置为单元测试的参数

How to set 2d array as parameter for unit testing

如果预期的变量是整数,它就像这样

[DataRow(2)]
[TestMethod]
public void TestMethod(int expected)
{
      // some code...
}

但是当有二维数组int[]而不是int参数时该怎么办呢? 当我尝试这样做时

[DataRow(new int[,] { {0, 0}, {0, 0} })]
[TestMethod]
public void TestMethod(int[,] expected)
{
      // some code...
}

错误说

An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type

您可以像下面这样使用 DynamicData Attribute 来实现它:

[DataTestMethod]
[DynamicData(nameof(TestDataMethod), DynamicDataSourceType.Method)]
public void TestMethod1(int[,] expected)
{
    // some code...
    var b = expected;
}

static IEnumerable<object[]> TestDataMethod()
{
    return new[] { new[] { new int[,] { { 0, 0 }, { 1, 1 } } } };
}

输出