title: Unit Testing Queries that passes Expression<Func<T,bool>> to Repository
body: <p>I'm having an issue really testing the Querying side of my architecture where I'm calling into a repository that expects an <code>Expression&lt;Func&lt;T, bool&gt;&gt;</code> as parameter for filtering. I was trying to understand this <a href="http://blog.ploeh.dk/2013/10/23/mocks-for-commands-stubs-for-queries/" rel="nofollow">article</a>, where Mark is saying to use Stubs for queries instead. </p>
  
  <p>Lets say I have a query handler:</p>
  
  <pre><code>public class GetUserByEmailQueryHandler : IQueryHandler&lt;GetUserByEmailQuery, User&gt;
  {
      private readonly IGenericRepository&lt;User&gt; userRepository;
  
      public GetUserByEmailQueryHandler(IGenericRepository&lt;User&gt; userRepository)
      {
          this.userRepository = userRepository;
      }
      public User Handle(GetUserByEmailQuery query)
      {
          return this.userRepository.Find(u =&gt; u.Email == query.Email &amp;&amp; u.IsLockedOut == false);
      }
  }
  </code></pre>
  
  <p>Now my test is going to look something like this:</p>
  
  <pre><code>    [Fact]
      public void Correctly_Returns_Result()
      {
          // arrange
          var id = Guid.NewGuid();
          var email = "test@test.com";
          var userRepositoryMock = new Mock&lt;IGenericRepository&lt;User&gt;&gt;();
          userRepositoryMock.Setup(
              r =&gt;
                  r.Find(It.IsAny&lt;Expression&lt;Func&lt;User, bool&gt;&gt;&gt;())).Returns(new User { UserId = id }).Verifiable();
  
          // Act
          var query = new GetUserByEmailQuery(email);
          var queryHandler = new GetUserByEmailQueryHandler(userRepositoryMock.Object);
          var item = queryHandler.Handle(query);
  
          // Assert
          userRepositoryMock.Verify();
          Assert.Equal(id, item.UserId);
      }
  </code></pre>
  
  <p>To me, this test is useless, especially using <code>It.IsAny&lt;Expression&lt;Func&lt;User, bool&gt;&gt;&gt;()</code> as I could be filtering by anything at all. The filter would be a crucial business logic that needs to be tested. How can I test an expression like this? Is this one of those reasons why a generic repository is bad and I should use a specific repository that take exactly the filter parameters that is needed? If that is the case, I'll be moving the expression from one layer to the other and I'd still need to test it</p>
  
  <p>If I should use stubs as Mark said in his blog, are there any examples out there? Am I supposed to run this query on an in-memory list which will be used to validate that the filter expression is correct?</p>