title: Mocking DbSet<T> inline
body: <p>I am using <code>.NET4.5</code>, <code>EF6</code>, and <code>Moq</code> for unit testing. I am trying to mock up some Db data for test. I have an example how to do this with declaring <a href="https://msdn.microsoft.com/en-gb/data/dn314429.aspx" rel="nofollow">mockset as variable and then using mocks.</a></p>
  
  <pre><code>public static class TestExtensionMethods
  {
         public static DbSet&lt;T&gt; AsDbSet&lt;T&gt;(this List&lt;T&gt; sourceList) where T : class
         {
             var queryable = sourceList.AsQueryable();
  
             var dbSet = new Mock&lt;DbSet&lt;T&gt;&gt;();
             dbSet.As&lt;IQueryable&lt;T&gt;&gt;().Setup(m =&gt; m.Provider).Returns(queryable.Provider);
             dbSet.As&lt;IQueryable&lt;T&gt;&gt;().Setup(m =&gt; m.Expression).Returns(queryable.Expression);
             dbSet.As&lt;IQueryable&lt;T&gt;&gt;().Setup(m =&gt; m.ElementType).Returns(queryable.ElementType);
             dbSet.As&lt;IQueryable&lt;T&gt;&gt;().Setup(m =&gt; m.GetEnumerator()).Returns(queryable.GetEnumerator());
             dbSet.Setup(d =&gt; d.Add(It.IsAny&lt;T&gt;())).Callback&lt;T&gt;(sourceList.Add);
             return dbSet.Object;
         }
  }
  </code></pre>
  
  <p>I am using it as extension method ATM like: <code>mockedDbContext.Journey = new List&lt;Journey&gt; { }.AsDbSet();</code></p>
  
  <p><strong>is there a way to declare it all as one-liner</strong> (so I could pass db sets as <code>TestCaseData</code> without need to write extension methods). I tried following</p>
  
  <pre><code>var mockedDbContext = new Mock&lt;OnlineLegal&gt;();
  mockedDbContext.Setup(o =&gt; o.Journey).Returns(() =&gt; (DbSet&lt;Journey&gt;)(new List&lt;Journey&gt; { new Journey { SessionId = sessionId, ConveyancingAnswer = new Collection&lt;ConveyancingAnswer&gt;()} }.AsEnumerable()));
  </code></pre>
  
  <p>but it blows up with <code>System.InvalidCastException : Unable to cast object of type 'System.Collections.Generic.List1[Saga.Services.Legal.Website.Journey]' to type 'System.Data.Entity.DbSet1[Saga.Services.Legal.Website.Journey]'.</code></p>
  
  <p><strong>How do I mock <code>DbSet&lt;T&gt;</code> inline?</strong></p>
  
  <p><strong>EDIT:</strong> In regards to duplication the guys who marked my question did not put effort into reading any further than title, and will get sarin gas from Santa this year.</p>