问题
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:
[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.
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?
回答1:
There is no built-in solution in MsTest BCL for comparing matrices. However there are several overloads which allows you to compare using a custom IComparer
:(BTW CollectionAssert
use those overloads internally...)
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());
来源:https://stackoverflow.com/questions/33188074/what-is-the-best-way-of-checking-the-matrix-value-in-unit-test