As you probably know I wrote two articles about mocking DbSet<TEntity> with Moq:
- synchronous calls – Mocking DbContext and DbSet with Moq
- asynchronous calls – EntityFramework – asynchronous queries unit tests
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:
- Create DbContextmock:
var userContextMock = new Mock<UsersContext>();
- Generate your entities:
IList<User> users = ...;
- 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; } }
Zasetupować ?
:). Masz jakąś inną propozycję?