7

I've got a method that converts a List to a DbSet which I use when mocking the data my database context should return. For example:

MockedDatabaseContext.Setup(u => u.SomeTable).Returns(GetDbSet(ListOfItems));

However the method I'm trying to write a unit test for uses the ToListAsync method at one point to convert from IQueryable to a List.

Is there a way using the Moq framework to make a setup on the ToListAsync method call?

I've tried this:

dbSet.Setup(d => d.ToListAsync(CancellationToken.None)).Returns((Task<List<T>>) Task.CompletedTask);

But this throws a 'ThrowIfSetupExpressionInvolvesUnsupportedMember' exception on the line above.

Rand Random
  • 7,300
  • 10
  • 40
  • 88
Jeroen
  • 1,625
  • 3
  • 16
  • 28
  • 3
    Not a real answer to your question, but, [the EF team](https://github.com/aspnet/EntityFrameworkCore/issues/6631) agrees that you should not attempt to mock EF. I'd suggest you to look at using the InMemory database package for testing. If you want to go down your route, note that you will have to implement most stuff manually – Camilo Terevinto Jan 17 '18 at 10:16
  • 2
    `ToListAsync` is an extension method, which wont work as Moq cannot setup/mock extension methods. – Nkosi Jan 17 '18 at 12:21
  • May be it is better for you to mock `DbSet` [this way](https://stackoverflow.com/questions/47775814/can-i-make-my-entity-framework-dbset-call-my-table-valued-function-when-selectin/47787125#47787125) – Slava Utesinov Jan 18 '18 at 06:17
  • 2
    This question has been answered: https://stackoverflow.com/questions/41324783/unit-testing-tolistasync-using-an-in-memory/41327224 – Ken Bonny Sep 23 '19 at 08:06
  • Does this answer your question? [Unit-testing .ToListAsync() using an in-memory](https://stackoverflow.com/questions/41324783/unit-testing-tolistasync-using-an-in-memory) – Cyril Durand Nov 11 '21 at 15:16

0 Answers0