Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SetupSequence in Moq

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

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, after the initial call, the method returns 1?

like image 633
Florian Avatar asked Jul 03 '12 09:07

Florian


People also ask

What is verifiable in MOQ?

Verifiable(); 'Setup' mocks a method and 'Returns' specify what the mocked method should return. 'Verifiable' marks this expectation to verified at the end when Verify or VerifyAll is called i.e. whether AddIncomePeriod was called with an object of IncomePeriod and if it returned the same output.


2 Answers

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

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

like image 79
Jakub Konecki Avatar answered Oct 22 '22 01:10

Jakub Konecki


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;                         }); 
like image 28
Romain Verdier Avatar answered Oct 22 '22 02:10

Romain Verdier