title: Moq with exact Expression<Func<TEntity, bool>>
body: <p>I am trying to test a Get method of a repository. The signature is as follows:</p>
  
  <pre><code>public virtual IEnumerable&lt;TEntity&gt; Get(
          Expression&lt;Func&lt;TEntity, bool&gt;&gt; filter = null,
          Func&lt;IQueryable&lt;TEntity&gt;, IOrderedQueryable&lt;TEntity&gt;&gt; orderBy = null,
          string includeProperties = "")
  </code></pre>
  
  <p>This method is usually invoked in the following manner: </p>
  
  <pre><code>Department targetDepartment =
              _departmentRepository.Get(department =&gt; department.Id == departmentId).FirstOrDefault();
  </code></pre>
  
  <p>It works fine with real data, it's when I try to setup this method to return a specific 'Department' with a specific lambda where the problems begin.</p>
  
  <p>So far, I have tried many ways to mock it and here are some of them:</p>
  
  <p>1)</p>
  
  <pre><code>Expression&lt;Func&lt;Department, bool&gt;&gt; filterExpression2 = d =&gt; d.Id == DepartmentId;
  
  _departmentRepositoryMock.Setup(repo =&gt; repo.Get(
      It.Is&lt;Expression&lt;Func&lt;Department, bool&gt;&gt;&gt;(y =&gt; filterExpression2.Compile()(firstDepartment)),
      null, 
      It.IsAny&lt;string&gt;()))
                           .Returns(new List&lt;Department&gt;() { firstDepartment }.AsQueryable());
  </code></pre>
  
  <p>2)</p>
  
  <pre><code>Expression&lt;Func&lt;Department, bool&gt;&gt; filterExpression2 = d =&gt; d.Id == DepartmentId;
  
  _departmentRepositoryMock.Setup(repo =&gt; repo.Get(
      It.IsAny&lt;Expression&lt;Func&lt;Department, bool&gt;&gt;&gt;(),
      null, 
      It.IsAny&lt;string&gt;()))
                           .Returns(new List&lt;Department&gt;() { firstDepartment }.Where(filterExpression2.Compile()).AsQueryable());
  </code></pre>
  
  <p>I saw many similar questions but somehow none of them is helpful.</p>
  
  <p>What I am trying to do is to force the mocked repository to return a specific Department depending on the 'Id' parameter sent to the lambda.</p>
  
  <p>I am aware of many responses using <code>It.IsAny</code>, but that it's not what I want as it would trigger a match on literally any expression passed into the Get method.</p>
  
  <p>Can anyone help me, or at least push me in the right direction?</p>