Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 917
AnonyMouse Avatar asked Aug 30 '12 01:08

AnonyMouse


3 Answers

Assert.IsTrue(Ids.SequenceEqual(Enumerable.Range(1, 3));

Tests not only that there are three numbers, but that there are the numbers 1, 2 and 3 in that order by making sure each element matches the corresponding element from Enumerable.Range(1, 3).

Edit: Combining the Range from here with with Kirill Polishchuk's answer, would suggest:

CollectionAssert.AreEqual(Enumerable.Range(1, 3), Ids);

If your Ids doesn't give an ordering, the simplest test for correctness is to apply that ordering in the test, bringing us back to being able to apply the above:

CollectionAssert.AreEqual(Enumerable.Range(1, 3), Ids.OrderBy(x => x));
like image 88
Jon Hanna Avatar answered Oct 15 '22 12:10

Jon Hanna


You can use LINQ extension methods for these needs:

using System.Linq;

…

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

Assert.IsTrue(Ids.Contains(1));
//etc.

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.

like image 45
Jay Avatar answered Oct 15 '22 12:10

Jay


Take a look at CollectionAssert class, it verifies true/false propositions associated with collections in unit tests.

like image 6
Kirill Polishchuk Avatar answered Oct 15 '22 10:10

Kirill Polishchuk