Created
June 22, 2017 21:44
-
-
Save costr/41ae069b724f72c9ecacb022d0ded5f8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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