开发者

Returning different results or throwing exceptions from successive calls to Moq Mock

开发者 https://www.devze.com 2023-01-04 03:33 出处:网络
I get a Moq object to return different values on successive calls to a method. This is done by this extension method:

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.


Nowadays Moq (version 4+) supports this through its SetupSequence method. See this post for an introduction.


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));


Phil Haack blogged about this.


Use SetupSequence(...) on the mock object.

For example the following will throw the exception on the first call and return someResponse on the second call:

myService.SetupSequence(s => s.PlaceOrder())
    .Throws(new Exception())
    .Returns(someResponse);
0

精彩评论

暂无评论...
验证码 换一张
取 消