如何创建涉及c#中集合的单元测试? [英] How can I create unit tests involving collections in c#?

查看:126
本文介绍了如何创建涉及c#中集合的单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些方法在C#中返回我想测试的各种集合。我想尽可能少使用测试API - 性能并不重要。一个典型的例子是:

I have a number of methods in C# which return various collections which I wish to test. I would like to use as few test APIs as possible - performance is not important. A typical example is:

HashSet<string> actualSet = MyCreateSet();
string[] expectedArray = new string[]{"a", "c", "b"};
MyAssertAreEqual(expectedArray, actualSet);

// ...

void MyAssertAreEqual(string[] expected, HashSet<string> actual)
{
    HashSet<string> expectedSet = new HashSet<string>();
    foreach {string e in expected)
    {
        expectedSet.Add(e);
    }
    Assert.IsTrue(expectedSet.Equals(actualSet));
}



我必须根据集合是否为数组来写多个签名,List,ICollections等。有没有简化这种转换(例如,将数组转换为Set?)。

I am having to write a number of signatures according to whether the collections are arrays, Lists, ICollections, etc. Are there transformations which simplify this (e.g. for converting an array to a Set?).

我还需要为自己的类。我已经为它们实现了HashCode和Equals。它们(主要)是从(比如)MySuperClass子类。可以实现功能:

I also need to do this for my own classes. I have implemented HashCode and Equals for them. They are (mainly) subclassed from (say) MySuperClass. Is it possible to implement the functionality:

void MyAssertAreEqual(IEnumerable<MySuperClass> expected, 
                      IEnumerable<MySuperClass> actual); 

,以便我可以调用:

IEnumerable<MyClassA> expected = ...;
IEnumerable<MyClassA> actual = ...; 
MyAssertAreEqual(expected, actual); 

而不是为每个类写这个

推荐答案

NUnit和MSTest(也可能是其他的)有一个CollectionAssert类

Both NUnit and MSTest (probably the other ones as well) have a CollectionAssert class

这篇关于如何创建涉及c#中集合的单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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