什么是检查在单元测试矩阵值的最佳方式? [英] What is the best way of checking the matrix value in Unit test?

查看:209
本文介绍了什么是检查在单元测试矩阵值的最佳方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是单元测试检查矩阵值的最佳方式。

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;
}



我想单元测试这个类使用Visual Studio的标准测试引擎,所以我创建单元测试,这样的事情:

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]);
    }
}



所以,在这里我写了一个断言来检查数量。在这两个矩阵的行相等,用来CollectionAssert检查矩阵中相应的行也相等

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?

推荐答案

有在MSTEST BCL比较矩阵没有内置的解决方案。然而,有几个重载,它允许您使用自定义比较的IComparer :( BTW CollectionAssert 内部使用这些重载.. 。)

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());

这篇关于什么是检查在单元测试矩阵值的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆