Last active
November 30, 2016 05:04
-
-
Save code-atom/d553c3a0beec5fcc12b1ae259b75c51a to your computer and use it in GitHub Desktop.
Create Fake DbSet from Moq Framework
This file contains hidden or 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 class Utility | |
{ | |
public static Mock<DbSet<TEntity>> GenerateMockEntity<TEntity>(List<TEntity> entityList) where TEntity : class | |
{ | |
var list = new List<TEntity>(); | |
list.AddRange(entityList); | |
var query = list.AsQueryable(); | |
var entityMockSet = new Mock<DbSet<TEntity>>() { CallBase = true}; | |
entityMockSet.As<IQueryable<TEntity>>().Setup(m => m.Provider).Returns(query.Provider); | |
entityMockSet.As<IQueryable<TEntity>>().Setup(m => m.Expression).Returns(query.Expression); | |
entityMockSet.As<IQueryable<TEntity>>().Setup(m => m.ElementType).Returns(query.ElementType); | |
entityMockSet.As<IEnumerable<TEntity>>().Setup(m => m.GetEnumerator()).Returns(query.GetEnumerator()); | |
entityMockSet.Setup(x => x.Add(It.IsAny<TEntity>())).Callback<TEntity>(x => { | |
list.Add(x); | |
entityMockSet.As<IEnumerable<TEntity>>().Setup(m => m.GetEnumerator()).Returns(list.GetEnumerator()); | |
}).Returns<TEntity>(x => x); | |
entityMockSet.Setup(x => x.AddRange(It.IsAny<IEnumerable<TEntity>>())).Callback<IEnumerable<TEntity>>(x => { | |
list.AddRange(x); | |
entityMockSet.As<IEnumerable<TEntity>>().Setup(m => m.GetEnumerator()).Returns(list.GetEnumerator()); | |
}); | |
entityMockSet.Setup(x => x.Remove(It.IsAny<TEntity>())).Callback<TEntity>(x => | |
{ | |
list.Remove(x); | |
entityMockSet.As<IEnumerable<TEntity>>().Setup(m => m.GetEnumerator()).Returns(list.GetEnumerator()); | |
}).Returns<TEntity>(x => x); | |
entityMockSet.Setup(x => x.RemoveRange(It.IsAny<IEnumerable<TEntity>>())).Callback<IEnumerable<TEntity>>(x => | |
{ | |
list.RemoveRange(x); | |
entityMockSet.As<IEnumerable<TEntity>>().Setup(m => m.GetEnumerator()).Returns(list.GetEnumerator()); | |
}); | |
return entityMockSet; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment