Search code examples
c#.netunit-testingrhino-mocksstub

How can I set a method of a Stub object to return 5 on the first call, and then 7 on the second call?


if you have an interface:

public interface ILuckynumberService
{
   int GetMyLuckyNumber();
}

And if you generate a stub for this interface like below, how can you enforce it to return 5 on the first call, then 7 on the second and 11 on the third call?

stubLuckyService = MockRepository.GenerateStub<ILuckyService>();
// Now, how to arrange stubLuckyService here?

Solution

  • Here is how I would do it, although there may be a more straight forward way of doing it:

    var results = new[] {5, 7, 11};
    var count = 0;
    service.Expect(x => x.GetMyLuckyNumber()).Return(0)
                                             .WhenCalled(x => { 
                                                    x.ReturnValue = results[count];
                                                    count++;
                                             });