EF Generic repository and Unit Of Work - unit testing using Moq
<p>In my application, I have the following DbContext:</p>

<pre><code>public class LibraryContext : DbContext
{
    public virtual DbSet&lt;LibraryUser&gt; LibraryUsers { get; set; }
    public virtual DbSet&lt;BookCollection&gt; BookCollections { get; set; }
    public virtual DbSet&lt;Book&gt; LibraryBooks { get; set; }

    public LibraryContext() : base("ExternalDB")
    {    
    }
}
</code></pre>

<p>Database resources are being managed by Unit of Work and Generic repository (based on <a href="https://www.asp.net/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application" rel="nofollow">ASP.NET's guidance</a>):</p>

<pre><code>public class UnitOfWork : IUnitOfWork, IDisposable
{
    private LibraryContext context = new LibraryContext();
    private GenericRepository&lt;BookCollection&gt; collectionRepository;
    private GenericRepository&lt;LibraryUser&gt; userRepository;
    private GenericRepository&lt;Book&gt; bookRepository;

    public GenericRepository&lt;BookCollection&gt; BookCollectionRepository
    {
        get
        {

            if (this.collectionRepository == null)
            {
                this.collectionRepository = new GenericRepository&lt;BookCollection&gt;(context);
            }
            return collectionRepository;
        }
    }

    public GenericRepository&lt;LibraryUser&gt; LibraryUserRepository
    {
        get
        {

            if (this.userRepository == null)
            {
                this.userRepository = new GenericRepository&lt;LibraryUser&gt;(context);
            }
            return userRepository;
        }
    }

    public GenericRepository&lt;Book&gt; BookRepository
    {
        get
        {

            if (this.bookRepository == null)
            {
                this.bookRepository = new GenericRepository&lt;Book&gt;(context);
            }
            return bookRepository;
        }
    }

    public void Save()
    {
        context.SaveChanges();
    }

    private bool disposed = false;

    protected virtual void Dispose(bool disposing)
    {
        if (!this.disposed)
        {
            if (disposing)
            {
                context.Dispose();
            }
        }
        this.disposed = true;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
}
</code></pre>

<p>The repository:</p>

<pre><code>public class GenericRepository&lt;TEntity&gt; where TEntity : class
{
    internal LibraryContext context;
    internal DbSet&lt;TEntity&gt; dbSet;

    public GenericRepository(LibraryContext context)
    {
        this.context = context;
        this.dbSet = context.Set&lt;TEntity&gt;();
    }

    public virtual IEnumerable&lt;TEntity&gt; Get(
        Expression&lt;Func&lt;TEntity, bool&gt;&gt; filter = null,
        Func&lt;IQueryable&lt;TEntity&gt;, IOrderedQueryable&lt;TEntity&gt;&gt; orderBy = null,
        string includeProperties = "")
    {
        IQueryable&lt;TEntity&gt; query = dbSet;

        if (filter != null)
        {
            query = query.Where(filter);
        }

        foreach (var includeProperty in includeProperties.Split
            (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
        {
            query = query.Include(includeProperty);
        }

        if (orderBy != null)
        {
            return orderBy(query).ToList();
        }
        else
        {
            return query.ToList();
        }
    }

    public virtual TEntity GetById(object id)
    {
        return dbSet.Find(id);
    }

    public virtual void Insert(TEntity entity)
    {
        dbSet.Add(entity);
    }

    public virtual void Delete(object id)
    {
        TEntity entityToDelete = dbSet.Find(id);
        Delete(entityToDelete);
    }

    public virtual void Delete(TEntity entityToDelete)
    {
        if (context.Entry(entityToDelete).State == EntityState.Detached)
        {
            dbSet.Attach(entityToDelete);
        }
        dbSet.Remove(entityToDelete);
    }

    public virtual void Update(TEntity entityToUpdate)
    {
        dbSet.Attach(entityToUpdate);
        context.Entry(entityToUpdate).State = EntityState.Modified;
    }
}
</code></pre>

<p>My controllers use UoW in the following way:</p>

<pre><code>public class HomeController : Controller
{
    IUnitOfWork uow;

    public HomeController() : this (new UnitOfWork())
    {
    }

    public HomeController(IUnitOfWork uow)
    {
        this.uow = uow;
    }

    public ActionResult Index()
    {
        if (Request.IsAuthenticated)
        {
            var books = uow.BookRepository.Get(filter:
                b =&gt; b.UserId.HasValue, orderBy:
                q =&gt; q.OrderBy(b =&gt; b.ReturnDate))
                .Take(50);
                //rest of the code
        }
        //rest of the code
    } 
//rest of the code
}
</code></pre>

<p>This all works just fine. Now I want to do some Unit Testing. Trying to make a fake <code>LibraryUsers DbSet</code>using Moq:</p>

<pre><code>class FakeUnitOfWork : IUnitOfWork
{

    Mock&lt;LibraryContext&gt; _mockContext;

    public FakeUnitOfWork()
    {
        InitFakeDbContext();
    }

    public GenericRepository&lt;LibraryUser&gt; LibraryUserRepository
    {
        get
        {
            return new GenericRepository&lt;LibraryUser&gt;(_mockContext.Object);
        }
    }

    public void Save()
    {
        throw new NotImplementedException();
    }

    public void InitFakeDbContext()
    {
        var data = FakeUsers.GetUsers(); // IQueryable&lt;LibraryUser&gt; data

        var mockSet = new Mock&lt;DbSet&lt;LibraryUser&gt;&gt;();
        mockSet.As&lt;IQueryable&lt;LibraryUser&gt;&gt;().Setup(m =&gt; m.Provider).Returns(data.Provider);
        mockSet.As&lt;IQueryable&lt;LibraryUser&gt;&gt;().Setup(m =&gt; m.Expression).Returns(data.Expression);
        mockSet.As&lt;IQueryable&lt;LibraryUser&gt;&gt;().Setup(m =&gt; m.ElementType).Returns(data.ElementType);
        mockSet.As&lt;IQueryable&lt;LibraryUser&gt;&gt;().Setup(m =&gt; m.GetEnumerator()).Returns(data.GetEnumerator());

        _mockContext = new Mock&lt;LibraryContext&gt;();
        _mockContext.Setup(c =&gt; c.LibraryUsers).Returns(mockSet.Object);
    }
    // rest of the code
}
</code></pre>

<p>But tests actually fail on <code>Generic Repository</code>'s <code>Get()</code>method (Value cannot be null). Debugging showed that issue occurs in the constructor:</p>

<pre><code>public GenericRepository(LibraryContext context)
{
    this.context = context;
    this.dbSet = context.Set&lt;TEntity&gt;(); // dbSet is actually null
}
</code></pre>

<p>Is there any way to fix it?</p>