SetupSequence in Moq

C#Unit TestingMockingMoq

C# Problem Overview


I want a mock that returns 0 the first time, then returns 1 anytime the method is called thereafter. The problem is that if the method is called 4 times, I have to write:

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

Otherwise, the method returns null.

Is there any way to write that, after the initial call, the method returns 1?

C# Solutions


Solution 1 - C#

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

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

Solution 2 - C#

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

Solution 3 - C#

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 [email protected] and [email protected] - passes ✔

Solution 4 - C#

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

Solution 5 - C#

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

Solution 6 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFlorianView Question on Stackoverflow
Solution 1 - C#Jakub KoneckiView Answer on Stackoverflow
Solution 2 - C#Romain VerdierView Answer on Stackoverflow
Solution 3 - C#Connor LowView Answer on Stackoverflow
Solution 4 - C#slothView Answer on Stackoverflow
Solution 5 - C#Thomas HeijtinkView Answer on Stackoverflow
Solution 6 - C#Tikiman163View Answer on Stackoverflow