title: Using Moq to mock Func<T> that behaves differently when called multiple times
body: <p>How can a C# Func be mocked so it returns different values or exceptions when invoked multiple times?</p>
  
  <pre><code>Mock&lt;Func&lt;bool&gt;&gt; mock = new Mock&lt;Func&lt;bool&gt;&gt;();
  mock.SetupSequence(m =&gt; m.Invoke())
      .Throws&lt;Exception&gt;()
      .Returns(true);
  </code></pre>
  
  <p>When run, the following exception is raised:</p>
  
  <pre><code>System.InvalidCastException : Unable to cast object of type
  System.Linq.Expressions.InstanceMethodCallExpressionN' to type
  'System.Linq.Expressions.InvocationExpression'.
  </code></pre>
  
  <p>I've seen another <a href="https://stackoverflow.com/questions/8755726/how-do-you-create-a-moq-mock-for-a-func/8756728#8756728">SO answer</a> about using <code>SetupSet</code>, however, I need a sequence.</p>