The following test case fails in rhino mocks:
[TestFixture]
public class EnumeratorTest
{
[Test]
public void Should_be_able_to_use_enumerator_more_than_once()
{
var numbers = MockRepository.GenerateStub<INumbers>();
numbers.Stub(x => x.GetEnumerator()).Return(new List<int>
{ 1, 2, 3 }.GetEnumerator());
var sut = new ObjectThatUsesEnumerator();
var correctResult = sut.DoSomethingOverEnumerator2Times
(numbers);
Assert.IsTrue(correctResult);
}
}
public class ObjectThatUsesEnumerator
{
public bool DoSomethingOverEnumerator2Times(INumbers numbers)
{
int sum1 = numbers.Sum(); // returns 6
int sum2 = numbers.Sum(); // returns 0 =[
return sum1 + sum2 == sum1 * 2;
}
}
public interface INumbers : IEnumerable<int> { }
I think there is something very subtle about this test case, and I think it is from me not thinking through how Rhino Mocks stubbing actually works. Typically, when you enumerate over an IEnumerable, you are starting with a fresh IEnumerator. In the example above, it looks like I could be re-using the same enumerator the second time I am calling sum, and if the enumerator is already at the end of its sequence, that would explain why the second call to Sum() returns 0. If this is the case, how could I mock out the GetEnumerator() in such a way that it behaves in the way that I am wanting it to (e.g. new enumerator or same enumerator reset to position 0)?
How would you modify the above test case so that the second .Sum() call actually returns 6 instead of 0?