Search code examples
c#entity-frameworkunit-testingrhino-mocksiqueryable

How to test asynchronous queries with rhino mocks


Following is my function

 public async Task<IEnumerable<Books>> GetAsync(Guid customerId) {
        var BookList= await _bookStore.FindBy(AnExpression(customerId)).ToListAsync();
        return vehicleList;
    }

I tried to mock the _bookStore.FindBy() Method which returns IQueryable

  var Books= new List<Books>(2){
                new Books(),
                new Books()
            }.AsQueryable();

 mock.Expect(viewStore => viewStore.FindBy(Arg<Expression<Func<Books, bool>>>.Is.Anything)).Return(Books);

viewStore is an interface:

public interface IRepository<T> : IDisposable where T : class
{
    IQueryable<T> FindBy(Expression<Func<T, bool>> predicate);
}

I am getting following error

System.InvalidOperationException: The source IQueryable doesn't implement IDbAsyncEnumerable. Only sources that implement IDbAsyncEnumerable can be used for Entity Framework asynchronous operations

I tried implementing AsyncQueryProvider like https://msdn.microsoft.com/en-us/data/dn314429#async

But the implementation is shown with Moq not with Rhino mock.


Solution

  • You have to use TestDbAsyncEnumerable which is implemented in the link you've provided.

    Replace:

    var Books= new List<Books>(2){
                new Books(),
                new Books()
            }.AsQueryable();
    
    mock.Expect(viewStore => viewStore.FindBy(Arg<Expression<Func<Books, bool>>>.Is.Anything))
        .Return(Books);
    

    with:

    var Books = new List<Books>(2){
                new Books(),
                new Books()
            }.AsQueryable();
    
    var asycEnumarable = new TestDbAsyncEnumerable<Books>(Books);
    
    var viewStore = MockRepository.GenerateStub<IRepository<Books>>();
    
    viewStore.Stub(x => x.FindBy(Arg<Expression<Func<Books, bool>>>.Is.Anything))
             .Return(asycEnumarable);