title: Moq testing LINQ Where queries
body: <p>I'm using EF 4.1 to build a domain model. I have a Task class with a Validate(string userCode) method and in it I want to ensure the user code maps to a valid user in the database, so:</p>
  
  <pre><code>public static bool Validate(string userCode)
  {
      IDbSet&lt;User&gt; users = db.Set&lt;User&gt;();
      var results = from u in users
                where u.UserCode.Equals(userCode)
                select u;
      return results.FirstOrDefault() != null;
  }
  </code></pre>
  
  <p>I can use Moq to mock IDbSet no problem. But ran into trouble with the Where call:</p>
  
  <pre><code>User user = new User { UserCode = "abc" };
  IList&lt;User&gt; list = new List&lt;User&gt; { user };
  var users = new Mock&lt;IDbSet&lt;User&gt;&gt;();
  users.Setup(x =&gt; x.Where(It.IsAny&lt;Expression&lt;Func&lt;User, bool&gt;&gt;&gt;())).Returns(list.AsQueryable);
  
  Initialization method JLTi.iRIS3.Tests.TaskTest.SetUp threw exception.
  System.NotSupportedException: System.NotSupportedException: Expression 
  references a method that does not belong to the mocked object:
  x =&gt; x.Where&lt;User&gt;(It.IsAny&lt;Expression`1&gt;()).
  </code></pre>
  
  <p>Other than creating a level of indirection (eg, using a ServiceLocator to get an object that runs the LINQ and then mock that method) I can't think of how else to test this, but I want to make sure there is no way before I introduce another layer. And I can see this kind of LINQ queries will be needed quite often so the service objects can quickly spiral out of control.</p>
  
  <p>Could some kind soul help? Thanks!</p>