title: Chaining methods with Moq
body: <p>I'm attempting to mock and setup chained methods using Moq.</p>
  
  <p>Here is the method I am trying to mock:</p>
  
  <pre><code>TeamMember teamMember = _unitOfWork
      .TeamMembers
      .Query()
      .ToList()
      .Where(t =&gt; t.AssociationCode.ToString() == code 
          &amp;&amp; Crypto.EncryptStringAES(t.Id.ToString(), sharedSecret) == hash)
      .SingleOrDefault();
  </code></pre>
  
  <p>and here is where I attempt to mock it:</p>
  
  <pre><code>var unitOfWorkMock = new Mock&lt;IUnitOfWork&gt;();
  var iQueryableMock = new Mock&lt;IQueryable&lt;TeamMember&gt;&gt;();
  var iToListMock = new Mock&lt;List&lt;TeamMember&gt;&gt;();
  var whereMock = new Mock&lt;IList&lt;TeamMember&gt;&gt;();
  var singleMock = new Mock&lt;IEnumerable&lt;TeamMember&gt;&gt;();
  
  unitOfWorkMock
      .Setup(u =&gt; u.TeamMembers
          .Query())
          .Returns(iQueryableMock.Object);
  
  iQueryableMock
      .Setup(i =&gt; i.ToList())
          .Returns(iToListMock.Object); //This line throws the error
  
  whereMock
      .Setup(w =&gt;
              w.Where(It.IsAny&lt;Func&lt;TeamMember, bool&gt;&gt;()))
          .Returns(singleMock.Object);
  
  singleMock
      .Setup(s =&gt;
              s.SingleOrDefault())
          .Returns(new TeamMember()
          {
              Email = "Test@TeamMember.com"
          });
  </code></pre>
  
  <p>When I run this test it gives me this error:</p>
  
  <blockquote>
    <p>Expression references a method that does not belong to the mocked object: <code>i =&gt; i.ToList&lt;TeamMember&gt;()</code></p>
  </blockquote>
  
  <p>I have looked at <a href="https://stackoverflow.com/questions/24719039/moq-chaining-expressions-results-in-parameter-count-mismatch">this question</a> already and have tried to do something similar, but I must be missing something.</p>
  
  <p>I am new to this, so if anyone can help me out it will be greatly appreciated. </p>