Moq to set up a function return based on called times

丶灬走出姿态 提交于 2019-11-30 11:05:10
TGH

Moq now has an extension method called SetupSequence() in the Moq namespace which means you can define a distinct return value for each specific call.

The general idea is that that you just chain the return values you need. In the example bellow the first call will return Joe and the second call will return Jane:

customerService
.SetupSequence(s => s.GetCustomerName(It.IsAny<int>()))
.Returns("Joe")   //first call
.Returns("Jane"); //second call

Some more info here.

Fredrik Mörk

I sometimes use a simple counter for such scenarios:

int callCounter = 0;
var mock = new Mock<IWhatever>();
mock.Setup(a => a.SomeMethod())
    .Returns(() => 
    {
       if (callCounter++ < 10)
       {
           // do something
       }
       else
       {
           // do something else
       }
    });

You can also set up a separate function to do this. You can even pass the function a parameter if you want:

_serviceMock.Setup(x => x.SomeMethod(It.IsAny<String>())).Returns((String param) => getTimesCalled(param));
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!