Answer the question
In order to leave comments, you need to log in
How to write tests in asp.net mvc without affecting Entity Framework?
How to mock EF without using an unnecessary layer of abstraction with repositories so that all the functionality of EF remains working? Now in the test I use this approach:
var mockSet = new Mock<DbSet<tarif>>();
var data = new List<tarif>
{
new tarif { id = 1, name = "Entity 1" },
new tarif { id = 2, name = "Entity 2" }
}.AsQueryable();
mockSet.As<IQueryable<tarif>>().Setup(m => m.Provider).Returns(data.Provider);
mockSet.As<IQueryable<tarif>>().Setup(m => m.Expression).Returns(data.Expression);
mockSet.As<IQueryable<tarif>>().Setup(m => m.ElementType).Returns(data.ElementType);
mockSet.As<IQueryable<tarif>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator());
var customDbContextMock = new Mock<callerEntities>();
customDbContextMock.Setup(x => x.tarifs).Returns(mockSet.Object);
Database.SqlQuery<GetSiteWidget_Result>("GetSiteWidgetAll").ToList()
Answer the question
In order to leave comments, you need to log in
Added mocking remove, removerange, add, addrange and put it into a generic method
public static DbSet<T> MockDbSet<T>(List<T> table) where T : class
{
var dbSet = new Mock<DbSet<T>>();
dbSet.As<IQueryable<T>>().Setup(q => q.Provider).Returns(() => table.AsQueryable().Provider);
dbSet.As<IQueryable<T>>().Setup(q => q.Expression).Returns(() => table.AsQueryable().Expression);
dbSet.As<IQueryable<T>>().Setup(q => q.ElementType).Returns(() => table.AsQueryable().ElementType);
dbSet.As<IQueryable<T>>().Setup(q => q.GetEnumerator()).Returns(() => table.AsQueryable().GetEnumerator());
dbSet.Setup(set => set.Add(It.IsAny<T>())).Callback<T>(table.Add);
dbSet.Setup(set => set.AddRange(It.IsAny<IEnumerable<T>>())).Callback<IEnumerable<T>>(table.AddRange);
dbSet.Setup(set => set.Remove(It.IsAny<T>())).Callback<T>(t => table.Remove(t));
dbSet.Setup(set => set.RemoveRange(It.IsAny<IEnumerable<T>>())).Callback<IEnumerable<T>>(ts =>
{
foreach (var t in ts) { table.Remove(t); }
});
return dbSet.Object;
}
How to mock EF without using an unnecessary layer of abstraction with repositories so that all the functionality of EF remains working?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question