Skip to content

Instantly share code, notes, and snippets.

@costr
Created June 22, 2017 21:44
Show Gist options
  • Save costr/41ae069b724f72c9ecacb022d0ded5f8 to your computer and use it in GitHub Desktop.
Save costr/41ae069b724f72c9ecacb022d0ded5f8 to your computer and use it in GitHub Desktop.
public static class RepositoryTestingHelper
{
public static DbSet<T> GetQueryableMockDbSet<T>(List<T> sourceList) where T : class
{
var dbSet = GetMockDbSet(sourceList);
return dbSet.Object;
}
public static Mock<DbSet<T>> GetMockDbSet<T>(List<T> entities) where T : class
{
var mockSet = new Mock<DbSet<T>>();
mockSet.As<IQueryable<T>>().Setup(q => q.Provider).Returns(() => entities.AsQueryable().Provider);
mockSet.As<IQueryable<T>>().Setup(q => q.Expression).Returns(() => entities.AsQueryable().Expression);
mockSet.As<IQueryable<T>>().Setup(q => q.ElementType).Returns(() => entities.AsQueryable().ElementType);
mockSet.As<IQueryable<T>>().Setup(q => q.GetEnumerator()).Returns(() => entities.AsQueryable().GetEnumerator());
mockSet.Setup(set => set.Add(It.IsAny<T>())).Callback<T>(entities.Add);
mockSet.Setup(set => set.AddRange(It.IsAny<IEnumerable<T>>())).Callback<IEnumerable<T>>(entities.AddRange);
mockSet.Setup(set => set.Remove(It.IsAny<T>())).Callback<T>(t => entities.Remove(t));
mockSet.Setup(set => set.RemoveRange(It.IsAny<IEnumerable<T>>())).Callback<IEnumerable<T>>(ts =>
{
foreach (var t in ts.ToList()) { entities.Remove(t); }
});
mockSet.Setup(set => set.AsNoTracking()).Returns(mockSet.Object);
return mockSet;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment