Search code examples
c#.netrhino-mocks

Rhino Mocks: How do I return numbers from a sequence


I have an Enumerable array

int meas[] = new double[] {3, 6, 9, 12, 15, 18};

On each successive call to the mock's method that I'm testing I want to return a value from that array.

using(_mocks.Record()) {
  Expect.Call(mocked_class.GetValue()).Return(meas); 
}
using(_mocks.Playback()) {
  foreach(var i in meas)
    Assert.AreEqual(i, mocked_class.GetValue();    
}

Does anyone have an idea how I can do this?


Solution

  • There is alway static fake object, but this question is about rhino-mocks, so I present you with the way I'll do it. The trick is that you create a local variable as the counter, and use it in your anonymous delegate/lambda to keep track of where you are on the array. Notice that I didn't handle the case that GetValue() is called more than 6 times.

    var meas = new int[] { 3, 6, 9, 12, 15, 18 };
    using (mocks.Record())
    {
        int forMockMethod = 0;
        SetupResult.For(mocked_class.GetValue()).Do(
            new Func<int>(() => meas[forMockMethod++])
            );
    }
    
    using(mocks.Playback())
    {
        foreach (var i in meas)
            Assert.AreEqual(i, mocked_class.GetValue());
    }