How to check IEnumerable <int>

in the test I need to test the object:

IEnumerable<int> Ids. 

The collection contains numbers 1,2 and 3.

Basically, I wanted to check that there are three identifiers in identifiers, and all of them are present in 1,2 and 3.

The problem is that there is no score on IEnumerable.

I thought I could go:

 Assert.AreEqual(3, Ids.Count); 

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

+4
source share
4 answers

For these purposes you can use LINQ extension methods:

 using System.Linq; … Assert.AreEqual(3, Ids.Count()); Assert.IsTrue(Ids.Contains(1)); //etc. 

If you want to have exactly the same elements in exactly the same order, there are also:

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

Ordering is not guaranteed according to IEnumerable<T> semantics, but this may not be the last in your specific scenario.

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

It checks not only that there are three numbers, but there are numbers 1, 2, and 3 in that order, making sure that each element corresponds to the corresponding element from Enumerable.Range(1, 3) .

Edit: Combining Range from here with Kirill Polishchuk's answer, suppose:

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

If your Ids does not give an order, the simplest criterion for correctness is to apply this order in a test, returning us to the possibility of applying the above:

 CollectionAssert.AreEqual(Enumerable.Range(1, 3), Ids.OrderBy(x => x)); 
+8
source

Take a look at the CollectionAssert class, it checks the true / false sentences associated with collections in unit tests.

+5
source

FluentAssertions are fantastic, providing a set of extension methods that help test:

Here is an excerpt from their documents

 IEnumerable collection = new[] { 1, 2, 5, 8 }; collection.Should().NotBeEmpty() .And.HaveCount(4) .And.ContainInOrder(new[] { 2, 5 }) .And.ContainItemsAssignableTo<int>(); collection.Should().Equal(new list<int> { 1, 2, 5, 8 }); collection.Should().Equal(1, 2, 5, 8); collection.Should().BeEquivalent(8, 2, 1, 5); collection.Should().NotBeEquivalent(8, 2, 3, 5); collection.Should().HaveCount(c => c > 3).And.OnlyHaveUniqueItems(); collection.Should().HaveSameCount(new[] {6, 2, 0, 5}); collection.Should().BeSubsetOf(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, }); collection.Should().Contain(8).And.HaveElementAt(2, 5).And.NotBeSubsetOf(new[] {11, 56}); collection.Should().Contain(x => x > 3); collection.Should().Contain(collection, 5, 6); // It should contain the original items, plus 5 and 6. collection.Should().OnlyContain(x => x < 10); collection.Should().OnlyContainItemsOfType<int>(); collection.Should().NotContain(82); collection.Should().NotContainNulls(); collection.Should().NotContain(x => x > 10); collection = new int[0]; collection.Should().BeEmpty(); 
+3
source

All Articles