SetupSequence in Moq

回眸只為那壹抹淺笑 提交于 2020-01-09 06:35:39

问题


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

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 the next times the method was called after the first time, the method returns 1 ? Thank you

Is it good to have more "operators" for SetupSequence ? If you think YES you can vote : http://moq.uservoice.com/forums/11304-general/suggestions/2973521-setupsequence-more-operators


回答1:


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



回答2:


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

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




回答3:


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



回答4:


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


来源:https://stackoverflow.com/questions/11308328/setupsequence-in-moq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!