0

How can a C# Func be mocked so it returns different values or exceptions when invoked multiple times?

Mock<Func<bool>> mock = new Mock<Func<bool>>();
mock.SetupSequence(m => m.Invoke())
    .Throws<Exception>()
    .Returns(true);

When run, the following exception is raised:

System.InvalidCastException : Unable to cast object of type
System.Linq.Expressions.InstanceMethodCallExpressionN' to type
'System.Linq.Expressions.InvocationExpression'.

I've seen another SO answer about using SetupSet, however, I need a sequence.

Community
  • 1
  • 1
Doug Domeny
  • 4,410
  • 2
  • 33
  • 49
  • 2
    I think your answer lies here: http://stackoverflow.com/questions/21297583/mocking-delegate-invoke-using-moq-throws-invalidcast-exception-in-linq – henrikmerlander Mar 16 '16 at 13:46

1 Answers1

2

With the tip to another answer from @henrikmerlander, the solution is to simply not use the .Invoke method.

Mock<Func<bool>> mock = new Mock<Func<bool>>();
    mock.SetupSequence(m => m())
        .Throws<Exception>()
        .Returns(true);
Doug Domeny
  • 4,410
  • 2
  • 33
  • 49