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.
Install-Package Moq.EntityFrameworkCore
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 can also use ReturnsDbSetWithGlobalFilter to set up a DbSet with a global filter. For example:
var users = new List<User> { new User { IsActive = true }, new User { IsActive = false } };
var userContextMock = new Mock<UsersContext>();
userContextMock.Setup(x => x.Users).ReturnsDbSetWithGlobalFilter(users, u => u.IsActive);You can now use the ReturnsDbSetDynamic method for scenarios where you need lazy evaluation of your DbSet. This ensures that the DbSet is re-evaluated dynamically at runtime.
userContextMock.Setup(x => x.Users).ReturnsDbSetDynamic(users);ReturnsDbSet: Statically resolves the DbSet value during setup.ReturnsDbSetDynamic: Dynamically resolves the DbSet value using a lambda, ensuring it reflects changes at runtime.
You will find examples of this library in the repository.