[英]What is the best way of checking the matrix value in Unit test?
What is the best way of checking the matrix value in Unit test? 在单元测试中检查矩阵值的最佳方法是什么?
I have a method in my project, something like this: 我的项目中有一个方法,如下所示:
int[][] getMatrix()
{
int[][] ans = new int[1][];
ans[0] = new int[1];
ans[0][0] = 0;
return ans;
}
I want to unit-test this class using visual studio standard testing engine, so I create a unit test, something like this: 我想使用Visual Studio标准测试引擎对此类进行单元测试,因此我创建了一个单元测试,如下所示:
[TestMethod]
public void Test()
{
var result = getMatrix();
int[][] correct = new int[1][];
correct[0] = new int[1];
correct[0] = 0;
Assert.AreEqual(correct.Length, result.Length);
for (int i = 0; i < correct.Length; ++i)
{
CollectionAssert.AreEqual(correct[i], result[i]);
}
}
So, here I wrote an assertion to check that number of lines in both matrices are equal and used CollectionAssert to check that corresponding rows of matrices are also equal. 因此,在这里我写了一个断言来检查两个矩阵中的行数是否相等,并使用CollectionAssert来检查对应的矩阵行是否相等。
I don't like this code - I'm sure there's some standard way of comparing matrices by values and the whole loop probably can be refactored in more short and clear way. 我不喜欢这段代码-我敢肯定,有一些标准的方法可以通过值比较矩阵,整个循环可能可以用更简短明了的方式进行重构。
So, what is the best way of checking the matrix value in unit test? 那么,在单元测试中检查矩阵值的最佳方法是什么?
There is no built-in solution in MsTest BCL for comparing matrices. MsTest BCL中没有用于比较矩阵的内置解决方案。 However there are several overloads which allows you to compare using a custom IComparer
:(BTW CollectionAssert
use those overloads internally...) 但是有一些重载,您可以使用自定义IComparer
进行比较:(BTW CollectionAssert
在内部使用这些重载...)
class CollectionAssertComperator : IComparer
{
public int Compare(object x, object y)
{
CollectionAssert.AreEqual((ICollection)x, (ICollection)y);
return 0;
}
}
Then you can simply use it:(and it is a reusable solution) 然后,您可以简单地使用它:(这是可重用的解决方案)
CollectionAssert.AreEqual(correct, result, new CollectionAssertComperator());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.