AnonyMouse AnonyMouse - 5 months ago 44
C# Question

How to test an IEnumerable<int>

in a test I need to test an object:

IEnumerable<int> Ids.

The collection contains the numbers 1,2 and 3.

I basically wanted to test that there are three ids in Ids and that 1,2 and 3 are all present.

The problem is there isn't a count on IEnumerable.

I thought I was going to be able to go:

Assert.AreEqual(3, Ids.Count);

Anyone know how to do this and how to ensure 1,2 and 3 are the actual numbers in there?

Jay Jay

You can use LINQ extension methods for these needs:

using System.Linq;


Assert.AreEqual(3, Ids.Count());


If you want to have exactly the same items in exactly the same order, there is also:

Assert.IsTrue(Ids.SequenceEqual(new List<int>{ 1, 2, 3 }));

Ordering is not guaranteed according to the semantics of IEnumerable<T>, but that may not be of consequence in your particular scenario.