Skip to content

Instantly share code, notes, and snippets.

@Kashkovsky
Created June 8, 2016 10:10
Show Gist options
  • Save Kashkovsky/a08979d288b311d2d8dda5b5747ed977 to your computer and use it in GitHub Desktop.
Save Kashkovsky/a08979d288b311d2d8dda5b5747ed977 to your computer and use it in GitHub Desktop.
Mock for abstract base repository
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