如何将2d数组设置为单元测试的参数

问题描述 投票:2回答:1

如果期望的变量是整数,则就像这样

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

但是当存在2d数组int [,]而不是int参数时,该怎么办?当我尝试执行此操作

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

错误说

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

c# unit-testing mstest data-driven-tests parameterized-unit-test
1个回答
1
投票

您可以使用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 } } } };
}

输出

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.