Alex Rivera | Logout

How to make a mock throw an exception the first time and return a value the second one

Asked 2011-10-27T17:26:37.373
9

I am using Moq as my mocking framework and I need to test a class that when a specific type of exception is run it will keep trying until the situation is resolved once that happens the execution finishes.

So what I need is something similar to:

myMock = Mock<IFoo>();

myMock.Setup(m => m.Excecute()).Throws<SpecificException>();
myMock.Setup(m => m.Execute());

var classUnderTest = MyClass(myMock);
classUnderTest.DoSomething();

Assert.AreEqual(expected, classUnderTest.Result);

Thanks for any help you can give.

Edit
Report

1 Answer

16

This is one way, based on the Moq QuickStart example of returning different values on each invocation.

var mock = new Mock<IFoo>();
var calls = 0;
mock.Setup(foo => foo.GetCountThing())
    .Returns(() => calls)
    .Callback(() =>
     {
        calls++;
        if (calls == 1)
        {
            throw new InvalidOperationException("foo");
        }
     });

try
{
    Console.WriteLine(mock.Object.GetCountThing());
}
catch (InvalidOperationException)
{
    Console.WriteLine("Got exception");
}

Console.WriteLine(mock.Object.GetCountThing());

If the method returns void, use:

var myMock = new Mock<IFoo>();
bool firstTimeExecuteCalled = true;

myMock.Setup(m => m.Execute())
      .Callback(() =>
       {
            if (firstTimeExecuteCalled)
            {
                firstTimeExecuteCalled = false;
                throw new SpecificException();
            }
       });

try
{
    myMock.Object.Execute();
}
catch (SpecificException)
{
    // Would really want to call Assert.Throws instead of try..catch.
    Console.WriteLine("Got exception");
}

myMock.Object.Execute();
Console.WriteLine("OK!");
answered 2011-10-27T17:36:46.547

Your Answer