Mock AsQueryable method with NSubstitute

33 Views Asked by At

I have a DAO class method that returns the Context object from EF Core 8.0:

public IQueryable<Operation> Select() =>
    context.Operations;

In a service class I have a method that performs an asynchronous search using the DAO class mentioned (no problem):

private async Task<IList<Operation>> GetPersistedOperations(List<int> ids, CancellationToken cancellationToken) =>
    await operationDao.Select()
                      .Include(o => o.FinancialLaunches)
                      .Where(o => ids.Contains(o.Id))
                      .ToListAsync(cancellationToken);

My problem is when I create a mock with NSubstitute from the DAO class, for the IQueryable<Operation>Select() method.

    var operations = Enumerable.Range(1, 3)
                               .Select(id => new Operation()
                               {
                                   Id = id,
                                   UnitId = 1,
                                   MovementType = "C",
                                   ForeignCurrencyDeliveringWayId = 1,
                                   NationalCurrencyValue = 30,
                                   Checked = "N",
                                   BacenBalanceDate = DateTime.Now.Date.AddDays(-1)
                               })
                               .AsQueryable();
    operationDao.Select().Returns(operations);

When my test passes through the GetPersistedOperations method that uses operationDao.Select() asynchronously (because of ToListAsync), I get this error:

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

I don't understand how I can mock the return to ToListAsync since the operationDao.Select() method expects a return from IQueryable<Operation>.

Any suggestions?

0

There are 0 best solutions below