0

I am writing some unit tests for my MVC 5 internet application. I have a service class that returns the following:

IEnumerable<Account>

I am writing a unit test to check the number of items in the returned IEnumerable<Account>.

Because IEnumerable does not have a .Count() function, how should I check the number of items in the returned IEnumerable? Should I convert this IEnumerable to a List, and then do the Count? Is there a better way or more official way to do this?

Thanks in advance.

Simon
  • 7,991
  • 21
  • 83
  • 163
  • 1
    It does have a [count method](http://stackoverflow.com/a/2659292/182821) via extension methods. – Chris Feb 02 '15 at 05:01

1 Answers1

1

IEnumerable<T> does have a Count() method, via LINQ.

Whether you call Count() or ToList().Count, the bottom line is the same: It's going to enumerate the entire collection. It doesn't matter which approach you use. The exception is if the underlying collection is an ICollection<T>. In that case, it will skip enumerating the entire collection and just return the Count property of the ICollection.

From a testing perspective, you probably don't care about the number of Accounts returned: You care that the correct Accounts were returned. I would rewrite my tests accordingly.

Daniel Mann
  • 57,011
  • 13
  • 100
  • 120