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?
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));
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.
Take a look at CollectionAssert
class, it verifies true/false propositions associated with collections in unit tests.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With