What is the best way of checking the matrix value in Unit test?

二次信任 提交于 2019-12-23 03:23:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!