Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Mocking Entity Framework Core operations such ToListAsync, FirstOrDefaultAsync etc. Author Raman Tsitou

License

Notifications You must be signed in to change notification settings

ramantsitou/MockQueryable

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

189 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

MockQueryable

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.


πŸ“¦ NuGet Packages

Package Latest Version Install via Package Manager
Download Version Install-Package MockQueryable.Core
Download Version Install-Package MockQueryable.EntityFrameworkCore
Download Version Install-Package MockQueryable.Moq
Download Version Install-Package MockQueryable.NSubstitute
Download Version Install-Package MockQueryable.FakeItEasy

βœ… Build & Status

codecov .NET Core License


⭐ GitHub Stats

Stars Contributors Last Commit Commit Activity Open Issues


πŸ’‘ Why Use MockQueryable?

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.

πŸš€ Getting Started

1. Create Test Data

var users = new List<UserEntity>
{
    new UserEntity { LastName = "Smith", DateOfBirth = new DateTime(2012, 1, 20) },
    // More test data...
};

2. Build the Mock

var mock = users.BuildMock(); // for IQueryable

3. Set Up in Your favorite Mocking Framework

Moq

_userRepository.Setup(x => x.GetQueryable()).Returns(mock);

NSubstitute

_userRepository.GetQueryable().Returns(mock);

FakeItEasy

A.CallTo(() => userRepository.GetQueryable()).Returns(mock);

πŸ—ƒοΈ Mocking DbSet<T>

var mockDbSet = users.BuildMockDbSet();

// Moq
var repo = new TestDbSetRepository(mockDbSet.Object);

// NSubstitute / FakeItEasy
var repo = new TestDbSetRepository(mockDbSet);

πŸ”§ Adding Custom Logic

Example: Custom FindAsync

mock.Setup(x => x.FindAsync(userId)).ReturnsAsync((object[] ids) =>
{
    var id = (Guid)ids[0];
    return users.FirstOrDefault(x => x.Id == id);
});

Example: Custom Expression Visitor

Build a mock with the custom SampleLikeExpressionVisitor for testing EF.Functions.Like

var mockDbSet = users.BuildMockDbSet<UserEntity, SampleLikeExpressionVisitor>();

🧩 Extend for Other Frameworks

You can even create your own extensions. Check the example here.


πŸ” Sample Project

See the sample project for working examples.