Mocking Entity Framework Core operations such ToListAsync, FirstOrDefaultAsync etc. Author Raman Tsitou
Mocking Entity Framework Core operations such ToListAsync, FirstOrDefaultAsync etc. Author Raman Tsitou
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:
var query = _userRepository.GetQueryable();
await query.AnyAsync(x => ...);
await query.FirstOrDefaultAsync(x => ...);
await query.ToListAsync();
// etc.MockQueryable creates a custom implementation of:
IQueryableIAsyncEnumerableIAsyncQueryProviderallowing EF Core async extensions to execute against in-memory collections.
See Architecture.
var users = new List
{
new UserEntity { LastName = "Smith", DateOfBirth = new DateTime(2012, 1, 20) },
// More test data...
};var mock = users.BuildMock(); // for IQueryable_userRepository.Setup(x => x.GetQueryable()).Returns(mock);_userRepository.GetQueryable().Returns(mock);A.CallTo(() => userRepository.GetQueryable()).Returns(mock);DbSetvar mockDbSet = users.BuildMockDbSet();
// Moq
var repo = new TestDbSetRepository(mockDbSet.Object);
// NSubstitute / FakeItEasy
var repo = new TestDbSetRepository(mockDbSet);FindAsyncmock.Setup(x => x.FindAsync(userId)).ReturnsAsync((object[] ids) =>
{
var id = (Guid)ids[0];
return users.FirstOrDefault(x => x.Id == id);
});Build a mock with the custom SampleLikeExpressionVisitor for testing EF.Functions.Like
var mockDbSet = users.BuildMockDbSet();You can even create your own extensions. Check the example here.
See the sample project for working examples.
No open issues yet, or sync has not completed.