hardywang hardywang - 1 year ago 70
C# Question

Moq to set up a function return based on called times

I need to mock an interface to call to MSMQ, is there a way I can use Moq to simulate real MSMQ scenario that there are 10 messages in the queue, I call mocked function 10 times and I can get a pre-defined object, on 11th time I should get a different return value (e.g. null)?

Answer Source

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:

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

Some more info here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download