Skip to content

.Should().BeEmpty() enumerates the sequence twice #124

@thomaslevesque

Description

@thomaslevesque

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();
        }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions