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)?
Asked
Active
Viewed 1.3k times
3 Answers
42
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.
-
It looks like the link is irrelevant :/ – tobiak777 Feb 12 '16 at 10:50
17
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
}
});

Jeremy Thompson
- 61,933
- 36
- 195
- 321

Fredrik Mörk
- 155,851
- 29
- 291
- 343
-
2Good solution. It is also possible to append `.CallBack( ... )` where the ellipsis represents delegate that modifies `callCounter` and possibly other state. – Jeppe Stig Nielsen Jan 16 '13 at 21:53
-
2
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));

Chris - Haddox Technologies
- 1,867
- 1
- 18
- 33