title: How to use Moq with Entity Framework IDbSet Count() etc. methods
body: <p>I'm trying to use <code>Moq</code> to make some tests for Entity Framework Code First classes. I'm very new to Moq and mocking techniques and I wonder if it's possible to easily do a test that I will describe below. I searched through the web for some solutions, but most are based on repository pattern, which I want to avoid.</p>
  
  <p>I have <code>ITestEntities</code> interface for context</p>
  
  <pre><code>public interface ITestEntities
  {
      IDbSet&lt;Order&gt; Orders { get; }
      IDbSet&lt;Product&gt; Products { get; }
      IDbSet&lt;User&gt; Users { get; }
  }
  </code></pre>
  
  <p>Then context</p>
  
  <pre><code>public class TestEntities : DbContext, ITestEntities
  {
      public TestEntities() : base("name=TestEntities")
      {
  
      }
  
      public virtual IDbSet&lt;Order&gt; Orders { get; set; }
      public virtual IDbSet&lt;Product&gt; Products { get; set; }
      public virtual IDbSet&lt;User&gt; Users { get; set; }
  }
  </code></pre>
  
  <p>A controller and an action to test</p>
  
  <pre><code>public class HomeController : Controller
  {
      private ITestEntities db;
  
      public HomeController()
      {
          db = new TestEntities();
      }
  
      public HomeController(ITestEntities db)
      {
          this.db = db;
      }
  
      public ActionResult Index()
      {
          var count = db.Users.Count();
          ViewBag.count = count;
  
          return View(count);
      }        
  }
  </code></pre>
  
  <p>And finally a NUnit test using Moq   </p>
  
  <pre><code>[Test]
  public void ModelValueShouldBeTwo()
  {
      var mockUsers = new Mock&lt;IDbSet&lt;User&gt;&gt;();
      mockUsers.Setup(m =&gt; m.Count()).Returns(2);
  
      var mockDB = new Mock&lt;ITestEntities&gt;();
      mockDB.Setup(db =&gt; db.Users).Returns((IDbSet&lt;User&gt;)mockUsers);
  
      var controller = new HomeController((ITestEntities)mockDB);
  
      var view = controller.Index();
  
      Assert.IsInstanceOf&lt;ViewResult&gt;(view);
      Assert.AreEqual(((ViewResult)view).Model, 2);
  }
  </code></pre>
  
  <p>The problem is with this line: <code>mockUsers.Setup(m =&gt; m.Count()).Returns(2);</code>. When running this test I get following error:</p>
  
  <p><code>System.NotSupportedException : Expression references a method that does not belong to the mocked object: m =&gt; m.Count&lt;User&gt;()</code></p>
  
  <p>I think this is due to <code>.Count()</code> being a static method so it cannot be mocked by Moq. Is there a way to test this simple action using Moq and not using full-fledged repository pattern, which as I understand should anyway have this <code>.Count()</code> part hardcoded into some method to be testable... Maybe I just use the mocks in a wrong way? Because I have impression that this should be quite simple and possible with EF Code First.</p>