C# Fake DbAsyncEnumerable (For Testing EntityFramework snippets)

Date: 2019-05-01
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;

namespace Domain.UnitTests
{
    public class DbAsyncEnumerator<T> : IDbAsyncEnumerator<T>
    {
        private readonly IEnumerator<T> _enumerator;
        public DbAsyncEnumerator(IEnumerator<T> enumerator)
        {
            _enumerator = enumerator;
        }
        public T Current => _enumerator.Current;
        object IDbAsyncEnumerator.Current => _enumerator.Current;
        public void Dispose()
        {
            _enumerator.Dispose();
        }
        public Task<bool> MoveNextAsync(CancellationToken cancellationToken)
        {
            return Task.FromResult(_enumerator.MoveNext());
        }
    }

    public class DbAsyncEnumerable<T> : IDbAsyncEnumerable<T>, IQueryable<T>
    {
        private readonly IQueryable<T> _queryable;
        private readonly IDbAsyncEnumerator<T> _dbEnumerator;
        public DbAsyncEnumerable(IQueryable<T> enumerable)
        {
            _queryable = enumerable;
            _dbEnumerator = new DbAsyncEnumerator<T>(enumerable.GetEnumerator());
        }
        public Expression Expression => _queryable.Expression;
        public Type ElementType => _queryable.ElementType;
        public IQueryProvider Provider => _queryable.Provider;
        public IDbAsyncEnumerator<T> GetAsyncEnumerator()
        {
            return _dbEnumerator;
        }
        public IEnumerator<T> GetEnumerator()
        {
            return _queryable.GetEnumerator();
        }
        IDbAsyncEnumerator IDbAsyncEnumerable.GetAsyncEnumerator()
        {
            return _dbEnumerator;
        }
        IEnumerator IEnumerable.GetEnumerator()
        {
            return _queryable.GetEnumerator();
        }
    }

// Usage: await repository.AsQueryable().Returns(new DbAsyncEnumerable<User>(userList.AsQueryable())).ToListAsync();
}

21270cookie-checkC# Fake DbAsyncEnumerable (For Testing EntityFramework snippets)