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

And*_*rey 3 c# unit-testing mstest data-driven-tests parameterized-unit-test

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

[DataRow(2)]
[TestMethod]
public void TestMethod(int expected)
{
      // some code...
}
Run Code Online (Sandbox Code Playgroud)

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

[DataRow(new int[,] { {0, 0}, {0, 0} })]
[TestMethod]
public void TestMethod(int[,] expected)
{
      // some code...
}
Run Code Online (Sandbox Code Playgroud)

错误说

属性参数必须是属性参数类型的常量表达式、typeof 表达式或数组创建表达式

Ngu*_*ong 5

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 } } } };
}
Run Code Online (Sandbox Code Playgroud)

输出

在此输入图像描述