title: How do I unit test a repository that uses DbContext with NSubstitute?
body: <p>I have a solution in which I have a Data project that contains an EF6 .edmx file, generated from an existing database. I split the entities into a separate Entities project, and have a Repositories project that references them both.</p>
  
  <p>I have added a BaseRepository with some common methods, and want to unit test it. The top of the class looks like this...</p>
  
  <pre><code>public class BaseRepository&lt;T&gt; : BaseRepositoryInterface&lt;T&gt; where T : class {
    private readonly MyEntities _ctx;
    private readonly DbSet&lt;T&gt; _dbSet;
  
    public BaseRepository(MyEntities ctx) {
      _ctx = ctx;
      _dbSet = _ctx.Set&lt;T&gt;();
    }
  
    public IEnumerable&lt;T&gt; GetAll() {
      return _dbSet;
    }
  
    //...
  }
  </code></pre>
  
  <p>Following the code I found at <a href="https://stackoverflow.com/a/21074664/706346">https://stackoverflow.com/a/21074664/706346</a>, I tried the following...</p>
  
  <pre><code>[TestMethod]
  public void BaseRepository_GetAll() {
    IDbSet&lt;Patient&gt; mockDbSet = Substitute.For&lt;IDbSet&lt;Patient&gt;&gt;();
    mockDbSet.Provider.Returns(GetPatients().Provider);
    mockDbSet.Expression.Returns(GetPatients().Expression);
    mockDbSet.ElementType.Returns(GetPatients().ElementType);
    mockDbSet.GetEnumerator().Returns(GetPatients().GetEnumerator());
    MyEntities mockContext = Substitute.For&lt;MyEntities&gt;();
    mockContext.Patients.Returns(mockDbSet);
  
    BaseRepositoryInterface&lt;Patient&gt; patientsRepository 
                            = new BaseRepository&lt;Patient&gt;(mockContext);
    List&lt;Patient&gt; patients = patientsRepository.GetAll().ToList();
    Assert.AreEqual(GetPatients().Count(), patients.Count);
  }
  
  private IQueryable&lt;Patient&gt; GetPatients() {
    return new List&lt;Patient&gt; {
      new Patient {
        ID = 1,
        FirstName = "Fred",
        Surname = "Ferret"
      }
    }
      .AsQueryable();
  }
  </code></pre>
  
  <p>Note that I changed the context TT file to use IDbSet, as suggested by Stuart Clement in his comment on Dec 4 '15 at 22:41</p>
  
  <p>However, when I run this test, it gives a null reference exception, as the line in the base repository constructor that sets <code>_dbSet</code> leaves it null...</p>
  
  <pre><code>_dbSet = _ctx.Set&lt;T&gt;();
  </code></pre>
  
  <p>I would guess I need to add another line when I set up my mock context, but I'm not sure what. I thought the code above should be enough to populate the DbSet.</p>
  
  <p>Anyone able to explain what I've missed or done wrong?</p>