Skip to content

Instantly share code, notes, and snippets.

@jeriley
Created March 23, 2015 02:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeriley/42f2a58300381e843ca0 to your computer and use it in GitHub Desktop.
Save jeriley/42f2a58300381e843ca0 to your computer and use it in GitHub Desktop.
DbContext Mocking example
namespace Moq.Context {
public static class DbContextMockExtension
{
public static Mock<AHContext> SetupPartOfTheContextWith<T>(this Mock<AHContext> mockContext, List<T> listOfT, Expression<Func<AHContext, DbSet<T>>> setupReturn) where T : BaseEntity
{
var queryable = listOfT.AsQueryable();
var mockSet = new Mock<DbSet<T>>();
mockSet.Setup(x => x.Add(It.IsAny<T>())).Callback((T entity) =>
{
listOfT.Add(entity);
entity.Id = listOfT.Max(x => x.Id) + 1;
});
mockSet.Setup(x => x.AddRange(It.IsAny<IEnumerable<T>>())).Callback((IEnumerable<T> entities) =>
{
var collection = entities as List<T> ?? entities.ToList();
listOfT.AddRange(collection);
collection.ForEach(entity => entity.Id = listOfT.Max(x => x.Id) + 1);
});
mockSet.As<IQueryable<T>>().Setup(m => m.Provider).Returns(queryable.Provider);
mockSet.As<IQueryable<T>>().Setup(m => m.Expression).Returns(queryable.Expression);
mockSet.As<IQueryable<T>>().Setup(m => m.ElementType).Returns(queryable.ElementType);
mockSet.As<IQueryable<T>>().Setup(m => m.GetEnumerator()).Returns(queryable.GetEnumerator());
mockContext.Setup(x => x.Set<T>()).Returns(mockSet.Object);
mockContext.Setup(setupReturn).Returns(mockSet.Object);
return mockContext;
}
}
}
public class Example {
private UnitOfWork _unitOfWork;
[TestInitialize]
public void Context()
{
var listOfStuff = new List<Items>{
//bunch of new stuff
}
var fakeContext = new Mock<ProjectDbContext>()
.SetupPartOfTheContextWith(listOfStuff, x => x.SomethingInTheDbContext);
_unitOfWork = new UnitOfWork(fakeContext.Object);
}
//some tests
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment