Moq 中的 SetupSequence

我想要一个模拟器,第一次返回 0,然后在随后调用该方法时返回 1。问题是,如果方法被调用4次,我必须写:

mock.SetupSequence(x => x.GetNumber())
.Returns(0)
.Returns(1)
.Returns(1)
.Returns(1);

否则,该方法返回 null。

有没有什么方法可以写出在初始调用之后,该方法返回 1

56932 次浏览

That's not particulary fancy, but I think it would work:

    var firstTime = true;


mock.Setup(x => x.GetNumber())
.Returns(()=>
{
if(!firstTime)
return 1;


firstTime = false;
return 0;
});

You can use a temporary variable to keep track of how many times the method was called.

Example:

public interface ITest
{ Int32 GetNumber(); }


static class Program
{
static void Main()
{
var a = new Mock<ITest>();


var f = 0;
a.Setup(x => x.GetNumber()).Returns(() => f++ == 0 ? 0 : 1);


Debug.Assert(a.Object.GetNumber() == 0);
for (var i = 0; i<100; i++)
Debug.Assert(a.Object.GetNumber() == 1);
}
}

The cleanest way is to create a Queue and pass .Dequeue method to Returns

.Returns(new Queue<int>(new[] { 0, 1, 1, 1 }).Dequeue);

Just setup an extension method like:

public static T Denqueue<T>(this Queue<T> queue)
{
var item = queue.Dequeue();
queue.Enqueue(item);
return item;
}

And then setup the return like:

var queue = new Queue<int>(new []{0, 1, 1, 1});
mock.Setup(m => m.GetNumber).Returns(queue.Denqueue);

Bit late to the party, but if you want to still use Moq's API, you could call the Setup function in the action on the final Returns call:

var mock = new Mock<IFoo>();
mock.SetupSequence(m => m.GetNumber())
.Returns(4)
.Returns(() =>
{
// Subsequent Setup or SetupSequence calls "overwrite" their predecessors:
// you'll get 1 from here on out.
mock.Setup(m => m.GetNumber()).Returns(1);
return 1;
});


var o = mock.Object;
Assert.Equal(4, o.GetNumber());
Assert.Equal(1, o.GetNumber());
Assert.Equal(1, o.GetNumber());
// etc...

I wanted to demonstrate using StepSequence, but for the OP's specific case, you could simplify and have everything in a Setup method:

mock.Setup(m => m.GetNumber())
.Returns(() =>
{
mock.Setup(m => m.GetNumber()).Returns(1);
return 4;
});

Tested everything here with xunit@2.4.1 and Moq@4.14.1 - passes ✔

Normally, I wouldn't bother submitting a new answer to such an old question, but in recent years ReturnsAsync has become very common, which makes potential answers more complicated.

As other have stated, you can essentially just create a queue of results and in your Returns call pass the queue.Dequeue delegate.

Eg.

var queue = new Queue<int>(new []{0,1,2,3});
mock.SetupSequence(m => m.Bar()).Returns(queue.Dequeue);

However, if you are setting up for an async method, we should normally call ReturnsAsync. queue.Dequeue when passed into ReturnsAsync and will result in the first call to the method being setup working correctly, but subsequent calls to throw a Null Reference Exception. You could as some of the other examples have done create your own extension method which returns a task, however this approach does not work with SetupSequence, and must use Returns instead of ReturnsAsync. Also, having to create an extension method to handle returning the results kind of defeats the purpose of using Moq in the first place. And in any case, any method which has a return type of Task where you have passed a delegate to Returns or ReturnsAsync will always fail on the second call when setting up via SetupSequence.

There are however two amusing alternatives to this approach that require only minimal additional code. The first option is to recognize that the Mock object's Setup and SetupAsync follow the Fluent Api design patterns. What this means, is that technically, Setup, SetupAsync, Returns and ReturnsAsync actually all return a "Builder" object. What I'm referring to as a Builder type object are fluent api style objects like QueryBuilder, StringBuilder, ModelBuilder and IServiceCollection/IServiceProvider. The practical upshot of this is that we can easily do this:

var queue = new List<int>(){0,1,2,3};
var setup = mock.SetupSequence(m => m.BarAsync());
foreach(var item in queue)
{
setup.ReturnsAsync(item);
}

This approach allows us to use both SetupSequence and ReturnsAsync, which in my opinion follows the more intuitive design pattern.

The second approach is to realize that Returns is capable of accepting a delegate which returns a Task, and that Setup will always return the same thing. This means that if we were to either create an an extension method for Queue like this:

public static class EMs
{
public static async Task<T> DequeueAsync<T>(this Queue<T> queue)
{
return queue.Dequeue();
}
}

Then we could simply write:

var queue = new Queue<int>(new []{0,1,2,3});
mock.Setup(m => m.BarAsync()).Returns(queue.DequeueAsync);

Or would could make use of the AsyncQueue class from Microsoft.VisualStudio.Threading, which would allow us to do this:

var queue = new AsyncQueue<int>(new []{0,1,2,3});
mock.Setup(m => m.BarAsync()).Returns(queue.DequeueAsync);

The main problem that causes all of this, as that when the end of a setup sequence has been reached, the method is treated as not being setup. To avoid this, you are expected to also call a standard Setup if results should be returned after the end of the sequence has been reached.

I have put together a fairly comprehensive fiddle regarding this functionality with examples of the errors you may encounter when doing things wrong, as well as examples of several different ways you can do things correctly. https://dotnetfiddle.net/KbJlxb

Moq uses the builder pattern, setting up the behavior of the mocks. You can, but don't have to use the fluent interface. Keeping that in mind, I solved the problem this way:

var sequence = myMock
.SetupSequence(""the method I want to set up"");


foreach (var item in stuffToReturn)
{
sequence = sequence.Returns(item);
}