title: Mock Generic Repository with contexts
body: <p>I have a generic repository for several contexts. I can extend it and use it for services without problem. However, When I mock it, <code>this.Entities</code> in the constructor is always <code>null</code>.</p>
  
  <p><strong>GenericDataRepsository</strong></p>
  
  <pre><code>public class GenericDataRepository&lt;T, C&gt; : IGenericDataRepository&lt;T, C&gt; where T : class where C : DbContext, new() {
  
      protected C context;
      protected IDbSet&lt;T&gt; Entities;
  
      public GenericDataRepository() {
          this.context = new C();
          this.Entities = context.Set&lt;T&gt;();
      }
  
      public GenericDataRepository(C context) {
          this.context = context;
          this.Entities = context.Set&lt;T&gt;();  // Problem is here. Entities didn't get set when mocking
      }
  
      public virtual IEnumerable&lt;T&gt; FindBy(Expression&lt;Func&lt;T, bool&gt;&gt; predicate) {
          return Entities.Where(predicate).ToList();
      }
  
      // omitted Add, Update, Delte
  }
  </code></pre>
  
  <p><strong>Unit Test</strong></p>
  
  <pre><code> [Test]
      public void GetBIlloTo() {
          var data = new List&lt;BillTo&gt; {
              new BillTo { CONTACTID = 12, COUNTRY = "USA" }
          }.AsQueryable();
  
          var mockSet = Substitute.For&lt;DbSet&lt;BillTo&gt;, IQueryable&lt;BillTo&gt;&gt;();
  
          ((IQueryable&lt;BillTo&gt;)mockSet).Provider.Returns(data.Provider);
          ((IQueryable&lt;BillTo&gt;)mockSet).Expression.Returns(data.Expression);
          ((IQueryable&lt;BillTo&gt;)mockSet).ElementType.Returns(data.ElementType);
  ((IQueryable&lt;BillTo&gt;)mockSet).GetEnumerator().Returns(data.GetEnumerator());
  
          var mockContext = Substitute.For&lt;MyEntities&gt;();
          mockContext.BillToes.Returns(mockSet);
          var repo = new GenericDataRepository&lt;BillTo, MyEntities&gt;(mockContext);
  
          //// Act
          var actual = repo.FindBy(r =&gt; r.CONTACTID == 12);
  
          //// Assert
          Assert.AreEqual(actual.Count(), 1);
      }
  </code></pre>
  
  <p><strong>MyEntities</strong> - generated by EF and I didn't change it.</p>
  
  <pre><code> public partial class MyEntities : DbContext
  {
      public MyEntities()
          : base("name=MyEntities")
      {
      }
  
      protected override void OnModelCreating(DbModelBuilder modelBuilder)
      {
          throw new UnintentionalCodeFirstException();
      }
  
      public virtual DbSet&lt;BillTo&gt; BillToes { get; set; }
  }
  </code></pre>
  
  <p>I'm using EF database first, NUnit, and Nsubstitute. Tried Moq as well, same problem. So, Why didn't <code>Entities</code> get set?</p>