How to create xunit test for Microsoft.EntityFrameworkCore 3.1 method FirstOrDefaultAsync?

.net-core c# entity-framework-core moq


This is my code block for a base repo.

public async Task<T> ReadAsync(Expression<Func<T, bool>> where = null)
   return await this.dbSet.Where(where).FirstOrDefaultAsync<T>();

I am getting this error,

EntityFrameworkQueryableExtensions.FirstOrDefaultAsync() may not be used in setup / verification expressions

enter image description here

2/21/2020 11:59:59 AM

Popular Answer

FirstOrDefaultAsync is an extension method, which are

a special kind of static method, but they are called as if they were instance methods on the extended type.

Mocking with Moq (I assume that it is Moq that you are using, as far as I can tell from what I see of your test methods) creates a proxy object derived from an interface of abstract class. Since the static extension method is not a part of your interface of abstract class, you can't mock that method. (See this question.)

Unfortunately, Where is an extension method, too, which means, that you cannot mock that, too.

Anyway, if the user repository does nothing more than providing an (encapsulated) extra layer around EF, I'd argue that mocking EF has no merit at all. Me too fell for the fallacy that everything has to be swappable and mocked out to unit-test classes, which is fine for logic (albeit not necessarily necessary, but that's another story), but questionable in your case.

2/21/2020 12:32:07 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow