Moq.EntityFrameworkCore 8.0.1.6

Moq.EntityFrameworkCore

Build Status Downloads

This library helps you mocking EntityFramework contexts. Now you will be able to test methods that are using DbSet<TEntity> or DbQuery<TEntity> from DbContext in an effective way.

Installation - NuGet Packages

Install-Package Moq.EntityFrameworkCore

Usage

For example we can assume that we have the following production code:

public class UsersContext : DbContext
{
    public virtual DbSet<User> Users { get; set; }
}

To mock Users and Roles you only need to implement the following 3 steps:

1. Create DbContext mock:

var userContextMock = new Mock<UsersContext>();

2. Generate your entities:

IList<User> users = ...;

3. Setup DbSet or DbQuery property:

userContextMock.Setup(x => x.Users).ReturnsDbSet(users);

or

userContextMock.SetupGet(x => x.Users).ReturnsDbSet(users);

or

userContextMock.SetupSequence(x => x.Set<User>())
  .ReturnsDbSet(new List<User>())
  .ReturnsDbSet(users);

And this is all. You can use your DbContext in your tests.

The second option is mocking DbSet that is part of the interface:

public interface IBlogContext
{
   DbSet<Post> Posts { get; }
}

And then use:

var posts = new List<Post>();
var contextMock = new Mock<IBlogContext>();
contextMock.Setup(p => p.Posts).ReturnsDbSet(posts);

You will find examples of this library in the repository.

No packages depend on Moq.EntityFrameworkCore.

Version 8.0.0.1 Added support for EntityFrameworkCore 8.0

.NET 8.0

Version Downloads Last updated
9.0.0.5 1 6/29/2025
9.0.0.1 1 2/28/2025
8.0.1.7 1 2/28/2025
8.0.1.6 1 2/28/2025
8.0.1.2 1 2/28/2025
8.0.1.1 1 2/28/2025
8.0.0.1 1 2/28/2025
7.0.0.2 5 8/6/2023
6.0.1.4 1 2/28/2025
6.0.1.3 1 2/28/2025
6.0.1.2 1 2/28/2025
6.0.0.6 1 2/28/2025
5.0.0.2 1 2/28/2025
5.0.0.1 1 2/28/2025
3.1.2.13 1 2/28/2025
3.1.2.6 1 2/28/2025
3.1.2.1 1 2/28/2025
3.0.0.10 1 2/28/2025
3.0.0.4 2 2/28/2025
2.2.1.1 1 2/28/2025
2.2.1 1 3/5/2025
2.0.1 2 3/5/2025
1.0.0 1 3/5/2025