tags:

views:

37

answers:

2

I get a Moq object to return different values on successive calls to a method. This is done by this extension method:

public static void ReturnsInOrder<T, TResult>(this ISetup<T, TResult> setup, params TResult[] results) where T : class
{
    setup.Returns(new Queue<TResult>(results).Dequeue);
}

Now I want one of the calls to throw an exception while others return something. Has anyone done this before?

If i do this

mock.Setup(m => m.SomeMethod())
    .Throws(new Exception());
mock.Setup(m => m.SomeMethod())
    .Returns("ok");

then the the first setup is overwritten and only the second setup persists.

+5  A: 

Phil Haack blogged about this.

Darin Dimitrov
A: 

I used callback chaining while developing retry proxy.

var src = new Mock<ITest>();
src.Setup(s => s.RaiseError()).Callback(() => 
src.Setup( s => s.RaiseError())).Throws<Exception>();

const int retryCount = 1;
var proxy = RetryProxy.MakeFor(src.Object, retryCount);

proxy.RaiseError();
src.Verify(s => s.RaiseError(), Times.Exactly(retryCount+1));
Ben