Skip to content

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: Total Downloads

PackageLatest VersionInstall via Package Manager
DownloadVersionInstall-Package MockQueryable.Core
DownloadVersionInstall-Package MockQueryable.EntityFrameworkCore
DownloadVersionInstall-Package MockQueryable.Moq
DownloadVersionInstall-Package MockQueryable.NSubstitute
DownloadVersionInstall-Package MockQueryable.FakeItEasy

✅ Build & Status

codecovbuildLicense


⭐ GitHub Stats

StarsContributorsLast CommitCommit ActivityOpen Issues


💡 Why Use MockQueryable?

Avoid hitting the real database in unit tests when querying via IQueryable:

varquery=_userRepository.GetQueryable();awaitquery.AnyAsync(x => ...);awaitquery.FirstOrDefaultAsync(x => ...);awaitquery.ToListAsync();// etc.

How It Works

MockQueryable creates a custom implementation of:

  • IQueryable<T>
  • IAsyncEnumerable<T>
  • IAsyncQueryProvider

allowing EF Core async extensions to execute against in-memory collections.

👷🏻‍See Architecture.


🚀 Getting Started

1. Create Test Data

varusers=newList<UserEntity>{newUserEntity{LastName="Smith",DateOfBirth=newDateTime(2012,1,20)},// More test data...};

2. Build the Mock

varmock=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>

varmockDbSet=users.BuildMockDbSet();// Moqvarrepo=newTestDbSetRepository(mockDbSet.Object);// NSubstitute / FakeItEasyvarrepo=newTestDbSetRepository(mockDbSet);

🔧 Adding Custom Logic

Example: Custom FindAsync

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

Example: Custom Expression Visitor

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

varmockDbSet=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.


Releases

Sponsor this project

Packages

Used by

Contributors

Languages