Mock Async Data Repository in ASP.NET Core 3.1
IAsyncQueryProvider interface in Entity Framework 5.0.3 has been changed. The interface method
Execute was replaced with
ExecuteAsync in the IdentityServer upgrade. Therefore, it will break the previously working unit tests using
IAsyncQueryProvider in ASP.NET core 2.2.
Before the update, the interface has this method:
public Task<TResult> ExecuteAsync<TResult> (System.Linq.Expressions.Expression expression, System.Threading.CancellationToken cancellationToken);
After the update, the interface method changed to:
public TResult ExecuteAsync<TResult> (System.Linq.Expressions.Expression expression, System.Threading.CancellationToken cancellationToken = default);
You can see the return type changed
Task<TResult> from to
TResult. If you only change the signature to match the new interface without other changes, you probably will get “Expression is not valid” error during the runtime.
Most of the information I found is based on .net core 2.2 until I found this one: https://stackoverflow.com/questions/57314896/iasyncqueryprovider-mock-issue-when-migrated-to-net-core-3-adding-tresult-iasyn. The code put inside ExecuteAsync worked for me.
The new IAsyncQueryProvider implementation:
The new IAsyncEnumerable implementation:
The new IAsyncEnumerator implementation:
Following code snippet shows how to mock DbSet<T> using the new IAsyncQueryProvider:
You can find the working solution in GitHub here.