views:

158

answers:

3

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?

+8  A: 

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)

Marc Gravell
So to translate it to something for the unit testing I could go Assert.IsTrue(result.SequenceEqual(expected));This doesn't supply a helpfull message, but it gets me there so that's ok.
borisCallens
@boris: It would be really easy to translate my (currently NUnit-based) code to the MS version. Then you get a nice message.
Jon Skeet
Yes, I had a look at it. I am currently a bit locked in in timing to experiment with unit testing as I'm doing it kind of unrequested (see OP). But I will try to squeeze in some of that.
borisCallens
+5  A: 

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 google code...

Jon Skeet
+1  A: 

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.

Davy Landman
Which takes an ICollection, not an IEnumerable... so you'd need to push it into a collection too...
Marc Gravell
@Marc Gravell, you're right.. I'll add it to the "answer"
Davy Landman