Posts

Showing posts from 2021

Mocking EntityFramework Core DbSet

EntityFramework Core introduces IQueryable<T> extensions for asynchronous DB operations, such as FirstAsync SingleOrDefaultAsync ToArrayAsync The problem is, when you need to mock an IQueryable in a unit test, and the test subject uses one of these new extensions you will get an error The provider for the source IQueryable doesn't implement IAsyncQueryProvider. Only providers that implement IAsyncQueryProvider can be used for Entity Framework asynchronous operations The solution can be found on various StackOverflow posts, but these are usually for EF 6, or an older version of EF Core. So here is a solution that works for EntityFramework Core 3.x When mocking services for your test subject, you can return any IEnumerable<T> as long as you use the extension AsAsyncQueryable();     using Microsoft.EntityFrameworkCore.Query.Internal; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threadi...