As you probably know I wrote two articles about mocking DbSet<TEntity> with Moq:

I combined those solution to one library and published in on NuGet – Moq.EntityFramework.Helpers.

In few words this library helps you with mocking EntityFramework contexts. Now you will be able to test methods that are using DbSet<TEntity> from DbContext in effective way.

Usage of this library is very easy. First you need to install it:

Install-Package Moq.EntityFramework.Helpers

After that you will only need to implement following 3 steps:

  1. Create DbContextmock:
var userContextMock = new Mock<UsersContext>();
  1. Generate your entities:
IList<User> users = ...;
  1. Setup DbSet propery:
userContextMock.Setup(x => x.Users).Returns(users);

And this is all. You can use your DbContext in your tests. More examples can be found at GitHub repository.

In example I used following DbContext:

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