Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

mocking

moq

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.

like image 847
ogborstad Avatar asked Jun 22 '10 13:06

ogborstad


1 Answers

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

like image 54
Clafou Avatar answered Oct 04 '22 18:10

Clafou