如何为测试方法提供 int[] 和 int 值,C#
How to provide int[,] and int values to test method, C#
我需要这个方法进行单元测试。有矩阵和计算整数矩阵迹的方法。所以我需要提供简单的矩阵 (int[]) 和预期的轨迹:
[DynamicData(nameof(TestDataMethod), DynamicDataSourceType.Method)]
public void TestReturnTrace(int[,] simpleMatrix, int expected)
{
var mock = new Mock<IMatrixGenerator>();
mock.Setup(a => a.GenerateRandomMatrix()).Returns(simpleMatrix);
MatrixBase matrix = new MatrixBase(mock.Object);
int actual = matrix.ReturnTrace();
Assert.AreEqual(expected, actual);
}
我如何创建简单的二维数组和整数值以及 return 它?
我最好的尝试是:
static IEnumerable<object[], int> TestDataMethod()
{
int[,] array2d = new int[,] { { 1, 0 }, { 0, 1 } };
int myInteger = 2;
return (new[] {
new[] { array2d },
myInteger )
};
}
但错误是 "No best type found for implicitly-typed array",就像我尝试创建数组一样,但我只是将两个值配对在括号中。我哪里错了?
您的 return 类型与方法数据不匹配,您可以使用 tuple
(int[,], int)
作为 IEnumerable<T>
和 yield return
的通用类型参数来return 一件商品。
static IEnumerable<(int[,], int)> TestDataMethod()
{
int[,] array2d = { { 1, 0 }, { 0, 1 } };
int myInteger = 2;
yield return (array2d, myInteger);
}
更新:刚刚看了一些关于 MSTest 和 DynamicData
属性的文章,比如 this。正确的方法似乎是使用 IEnumerable<object[]>
,其中对象数组中的每个项目代表测试方法
中的单个参数
static IEnumerable<object[]> TestDataMethod()
{
int[,] array2d = { { 1, 0 }, { 0, 1 } };
int myInteger = 2;
yield return new object[] { array2d, myInteger };
}
我需要这个方法进行单元测试。有矩阵和计算整数矩阵迹的方法。所以我需要提供简单的矩阵 (int[]) 和预期的轨迹:
[DynamicData(nameof(TestDataMethod), DynamicDataSourceType.Method)]
public void TestReturnTrace(int[,] simpleMatrix, int expected)
{
var mock = new Mock<IMatrixGenerator>();
mock.Setup(a => a.GenerateRandomMatrix()).Returns(simpleMatrix);
MatrixBase matrix = new MatrixBase(mock.Object);
int actual = matrix.ReturnTrace();
Assert.AreEqual(expected, actual);
}
我如何创建简单的二维数组和整数值以及 return 它?
我最好的尝试是:
static IEnumerable<object[], int> TestDataMethod()
{
int[,] array2d = new int[,] { { 1, 0 }, { 0, 1 } };
int myInteger = 2;
return (new[] {
new[] { array2d },
myInteger )
};
}
但错误是 "No best type found for implicitly-typed array",就像我尝试创建数组一样,但我只是将两个值配对在括号中。我哪里错了?
您的 return 类型与方法数据不匹配,您可以使用 tuple
(int[,], int)
作为 IEnumerable<T>
和 yield return
的通用类型参数来return 一件商品。
static IEnumerable<(int[,], int)> TestDataMethod()
{
int[,] array2d = { { 1, 0 }, { 0, 1 } };
int myInteger = 2;
yield return (array2d, myInteger);
}
更新:刚刚看了一些关于 MSTest 和 DynamicData
属性的文章,比如 this。正确的方法似乎是使用 IEnumerable<object[]>
,其中对象数组中的每个项目代表测试方法
static IEnumerable<object[]> TestDataMethod()
{
int[,] array2d = { { 1, 0 }, { 0, 1 } };
int myInteger = 2;
yield return new object[] { array2d, myInteger };
}