Skip to content

romantitov/MockQueryable

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

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 Downloads Latest Version Install via Package Manager
MockQueryable.Core Downloads Version Install-Package MockQueryable.Core
MockQueryable.EntityFrameworkCore Downloads Version Install-Package MockQueryable.EntityFrameworkCore
MockQueryable.Moq Downloads Version Install-Package MockQueryable.Moq
MockQueryable.NSubstitute Downloads Version Install-Package MockQueryable.NSubstitute
MockQueryable.FakeItEasy Downloads Version Install-Package MockQueryable.FakeItEasy

βœ… Build & Status

.NET Core AppVeyor 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.