简体   繁体   English

如何在c#中创建涉及集合的单元测试?

[英]How can I create unit tests involving collections in c#?

I have a number of methods in C# which return various collections which I wish to test. 我在C#中有许多方法可以返回我希望测试的各种集合。 I would like to use as few test APIs as possible - performance is not important. 我想尽可能少地使用测试API - 性能并不重要。 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));
}

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 (eg for converting an array to a Set?). 我必须根据集合是否是数组,列表,ICollections等来编写许多签名。是否存在简化此操作的转换(例如,将数组转换为Set?)。

I also need to do this for my own classes. 我还需要为自己的课程这样做。 I have implemented HashCode and Equals for them. 我已经为他们实现了HashCode和Equals。 They are (mainly) subclassed from (say) MySuperClass. 它们(主要)是(比如)MySuperClass的子类。 Is it possible to implement the functionality: 是否可以实现该功能:

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

such that I can call: 这样我可以打电话:

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

rather than writing this for every class 而不是为每个班级写这个

Both NUnit and MSTest (probably the other ones as well) have a CollectionAssert class NUnit和MSTest(可能还有其他的)都有一个CollectionAssert类

If you are using .NET 3.5 you can use the Enumerable.SequenceEqual method. 如果您使用的是.NET 3.5,则可以使用Enumerable.SequenceEqual方法。

Assert.IsTrue(seqA.SequenceEqual(seqB));

You should use OrderBy on both sequences prior to calling SequenceEqual if you only care about the elements being equal and not the order. 如果只关心元素相等而不是顺序,则应在调用SequenceEqual之前在两个序列上使用OrderBy。

Have you tried using the CollectionAssert that comes with NUnit. 您是否尝试过使用NUnit附带的CollectionAssert

It asserts against the two collections and compares the items within the collection 它对两个集合断言并比较集合中的项目

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM