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
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...
There is a simple but not obvious way to do this with NUnit 3+ 'constraint' assertions:
Assert.That(result, Is.EqualTo(expected).AsCollection, "My failure message");
This will give you the same as the linq mentioned in other answers:
Assert.That(result.SequenceEqual(expected), "My failure message");
But the AsCollection
version will tell you where the first difference is, and if the lengths are different.
See https://docs.nunit.org/articles/nunit/writing-tests/constraints/EqualConstraint.html#comparing-arrays-collections-and-ienumerables
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)
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.