Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assert IEnumerables

As unit testing is not used in our firm, I'm teaching myself to unit test my own code. I'm using the standard .net test framework for some really basic unit testing.

A method of mine returns a IEnumerable<string> and I want to test it's output. So I created an IEnumerable<string> expected to test it against. I thought I remembered there to be a way to Assert.ArePartsEqual or something like that, but I can't seem to find it.

So in short, how do I test if two IEnumerable<string> contain the same strings?

like image 939
Boris Callens Avatar asked Feb 13 '09 11:02

Boris Callens


3 Answers

I don't know which "standard .net test framework" you're referring to, but if it's Visual Studio Team System Unit testing stuff you could use CollectionAssert.

Your test would be like this:

CollectionAssert.AreEqual(ExpectedList, ActualList, "...");

Update: I forgot CollectionAssert needs an ICollection interface, so you'll have to call ActualList.ToList() to get it to compile. Returning the IEnumerable is a good thing, so don't change that just for the tests.

like image 174
Davy Landman Avatar answered Sep 20 '22 19:09

Davy Landman


You want the SequenceEqual() extension method (LINQ):

    string[] x = { "abc", "def", "ghi" };
    List<string> y = new List<string>() { "abc", "def", "ghi" };

    bool isTrue = x.SequenceEqual(y);

or just:

   bool isTrue = x.SequenceEqual(new[] {"abc","def","ghi"});

(it will return false if they are different lengths, or any item is different)

like image 45
Marc Gravell Avatar answered Sep 20 '22 19:09

Marc Gravell


I have an example of this I used for my "Implementing LINQ to Objects in 60 minutes" talk.

It also in my MoreLinq project. Having tried to c'n'p it in here, it wraps horribly. Just grab from Github...

like image 34
Jon Skeet Avatar answered Sep 21 '22 19:09

Jon Skeet