Extensions for mocking Entity Framework Core async queries like ToListAsync, FirstOrDefaultAsync, and more using popular mocking libraries such as Moq, NSubstitute, and FakeItEasy — all without hitting the database.
❤️ If you really like the tool, please 👉 Support the project or ☕ Buy me a coffee.
Avoid hitting the real database in unit tests when querying via IQueryable:
varquery=_userRepository.GetQueryable();awaitquery.AnyAsync(x => ...);awaitquery.FirstOrDefaultAsync(x => ...);awaitquery.ToListAsync();// etc.MockQueryable creates a custom implementation of:
IQueryable<T>IAsyncEnumerable<T>IAsyncQueryProvider
allowing EF Core async extensions to execute against in-memory collections.
👷🏻See Architecture.
varusers=newList<UserEntity>{newUserEntity{LastName="Smith",DateOfBirth=newDateTime(2012,1,20)},// More test data...};varmock=users.BuildMock();// for IQueryable_userRepository.Setup(x =>x.GetQueryable()).Returns(mock);_userRepository.GetQueryable().Returns(mock);A.CallTo(()=>userRepository.GetQueryable()).Returns(mock);varmockDbSet=users.BuildMockDbSet();// Moqvarrepo=newTestDbSetRepository(mockDbSet.Object);// NSubstitute / FakeItEasyvarrepo=newTestDbSetRepository(mockDbSet);mock.Setup(x =>x.FindAsync(userId)).ReturnsAsync((object[]ids)=>{varid=(Guid)ids[0];returnusers.FirstOrDefault(x =>x.Id==id);});Build a mock with the custom SampleLikeExpressionVisitor for testing EF.Functions.Like
varmockDbSet=users.BuildMockDbSet<UserEntity,SampleLikeExpressionVisitor>();You can even create your own extensions. Check the example here.
See the sample project for working examples.