Moq – Mocking the same method call with multiple results

moq logo

The Scenario

I have a loop in production code that has evolved into processing batches of records. I need to modify an existing unit test to accommodate mocking the same method call each time through the loop returning different results on each loop (as it would in production).

The Solution

Using Moq we can make use of a Queue and Dequeue result sets each time in the loop as follows:

for (var i = 0; i < loop; i++)


var jobsInBatch = BuildJobs(batches).ToList();




_processor.Setup(m => m.GetAllJobs(batches)).Returns(() => jobQueue.Dequeue());

Leave a Reply

%d bloggers like this: