Created
June 8, 2016 10:10
-
-
Save Kashkovsky/a08979d288b311d2d8dda5b5747ed977 to your computer and use it in GitHub Desktop.
Mock for abstract base repository
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
using System.Collections.Generic; | |
using System.Data.Entity; | |
using System.Linq; | |
using Moq; | |
namespace Test.Common.Mock.Repository | |
{ | |
public abstract class MockBaseRepository<T, TEntity> : Mock<T> | |
where TEntity : class, IEntity | |
where T : BaseRepository<TEntity> | |
{ | |
protected IList<TEntity> Data { get; set; } | |
protected MockBaseRepository() | |
{ | |
Init(); | |
} | |
protected void Init() | |
{ | |
GenerateEntities(); | |
Setup(x => x.Data).Returns(MockDbSet().Object); | |
Setup(x => x.CreateOrUpdate(It.IsAny<TEntity>())).Callback((TEntity entity) => Data.Add(entity)); | |
Setup(x => x.Delete(It.IsAny<TEntity>())).Callback((TEntity entity) => Data.Remove(entity)); | |
Setup(x => x.GetAll()).Returns(Data.ToList()); | |
Setup(x => x.All).Returns(Data.AsQueryable()); | |
Setup(x => x.GetById(It.IsAny<int>())).Returns((int id) => Data.FirstOrDefault(x => x.Id == id)); | |
} | |
protected virtual void GenerateEntities() | |
{ | |
Data = new List<TEntity>(); | |
} | |
private Mock<IDbSet<TEntity>> MockDbSet() | |
{ | |
var data = Data.AsQueryable(); | |
var dbSetMock = new Mock<IDbSet<TEntity>>(); | |
dbSetMock.Setup(m => m.Provider).Returns(data.Provider); | |
dbSetMock.Setup(m => m.Expression).Returns(data.Expression); | |
dbSetMock.Setup(m => m.ElementType).Returns(data.ElementType); | |
dbSetMock.Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator()); | |
return dbSetMock; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment