-
Notifications
You must be signed in to change notification settings - Fork 732
.Should().BeEmpty() enumerates the sequence twice #124
Copy link
Copy link
Closed
Milestone
Description
It's usually considered good practice to avoid enumerating enumerables multiple times, unless they are known to be materialized (e.g. IList or ICollection). So I have a ForbidMultipleEnumeration extension method that I use in my unit tests to ensure that the methods that work on sequences enumerate them only once. Apparently .Should().BeEmpty() enumerates the sequence twice, which breaks the tests.
Here's an example of a test that fails because of that:
[Test]
public void Dummy()
{
var source = Enumerable.Empty<int>().ForbidMultipleEnumeration();
source.Should().BeEmpty();
}And here's the implementation of ForbidMultipleEnumeration:
static class Extensions
{
public static IEnumerable<TSource> ForbidMultipleEnumeration<TSource>(this IEnumerable<TSource> source, string message = "Sequence shouldn't be enumerated more than once.")
{
return new SingleEnumerationEnumerable<TSource>(source, message);
}
[ExcludeFromCodeCoverage]
private class SingleEnumerationEnumerable<TSource> : IEnumerable<TSource>
{
private readonly IEnumerable<TSource> _source;
private readonly string _message;
private bool _enumerated;
public SingleEnumerationEnumerable(IEnumerable<TSource> source, string message)
{
_source = source;
_message = message;
}
public IEnumerator<TSource> GetEnumerator()
{
if (_enumerated)
throw new InvalidOperationException(_message);
_enumerated = true;
return _source.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels