title: How to set up a method twice for different parameters with Moq
body: <p>I would like to set up a method with Moq twice but it seems that the last one overrides the previous ones. Here's my initial setup:</p>
  
  <pre><code>string username = "foo";
  string password = "bar";
  
  var principal = new GenericPrincipal(
      new GenericIdentity(username),
      new[] { "Admin" });
  
  var membershipServiceMock = new Mock&lt;IMembershipService&gt;();
  membershipServiceMock.Setup(ms =&gt;
      ms.ValidateUser(username, password)
  ).Returns(new ValidUserContext { 
      Principal = principal
  });
  </code></pre>
  
  <p>This works out fine but I want this to return <code>new ValidUserContext()</code> if the username or password is different to the <code>username</code> and <code>password</code> variables as above. To do that, I added another setup but this time it overrides the above one and always applies it:</p>
  
  <pre><code>membershipServiceMock.Setup(ms =&gt;
      ms.ValidateUser(It.IsAny&lt;string&gt;(), It.IsAny&lt;string&gt;())
  ).Returns(
      new ValidUserContext()
  );
  </code></pre>
  
  <p>What is the most elegant way of handling this type of situation with Moq?</p>
  
  <p><strong>Edit</strong></p>
  
  <p>I solved the problem with the below approach but I guess there is a better way of handling this:</p>
  
  <pre><code>var membershipServiceMock = new Mock&lt;IMembershipService&gt;();
  membershipServiceMock.Setup(ms =&gt;
      ms.ValidateUser(It.IsAny&lt;string&gt;(), It.IsAny&lt;string&gt;())
  ).Returns&lt;string, string&gt;((u, p) =&gt; 
      (u == username &amp;&amp; p == password) ?
      new ValidUserContext { 
          Principal = principal
      }
      : new ValidUserContext()
  );
  </code></pre>