C#使用多维数组作为DataRow(MSTest)的输入



我目前正在构建一个测试项目,需要向测试函数传递几个参数。因为我需要用不同的参数集调用测试函数,所以我决定使用带有[DataTestMethod]的ms测试。现在,我需要将锯齿状数组作为参数传递给函数。但我不能让它发挥作用。对TestMethod1的调用正在工作。对TestMethod2的调用不起作用,因为它没有成功编译。

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

using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace UnitTestProject2
{
[TestClass]
public class UnitTest1
{
[DataTestMethod]
[DataRow(new int[] { })]
public void TestMethod1(int[] values)
{
}
[DataTestMethod]
[DataRow(new int [][] { } )]
public void TestMethod2(int[][] values)
{

}
}
}

有人有什么建议吗?遗憾的是,我需要使用某种二维数据类型,因为我需要在测试函数内部传递有关两个循环的信息。我不能使用params关键字,因为我在测试函数中需要两个这样的锯齿状数组。

问候白色

不能将锯齿状数组用作属性中的参数,因为不能将其声明为const。更多解释在这里:Const多维数组初始化

出于您的目的,我将使用DynamicDataAttribute:

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
namespace UnitTestProject
{
[TestClass]
public class TestClass
{
static IEnumerable<int[][][]> GetJaggedArray
{
get
{
return new List<int[][][]>
{
new int[][][]
{
new int [][]
{
new int[] { 1 },
new int[] { 2, 3, 4 },
new int[] { 5, 6 }
}
}
};
}
}
[TestMethod]
[DynamicData(nameof(GetJaggedArray))]
public void Test1(int[][] jaggedArray)
{
Assert.AreEqual(1, jaggedArray[0][0]);
Assert.AreEqual(2, jaggedArray[1][0]);
Assert.AreEqual(3, jaggedArray[1][1]);
Assert.AreEqual(4, jaggedArray[1][2]);
Assert.AreEqual(5, jaggedArray[2][0]);
Assert.AreEqual(6, jaggedArray[2][1]);
}
}
}

我知道语法IEnumerable<int[][][]>并不令人愉快,但由于DynamicDataAttribute。GetData(MethodInfo(方法返回IEnumerable<object[]>,而您的objectint[][],这就是您得到的。

最新更新