Search code examples
c#rhino-mocks

With Rhino Mocks should BackToRecord() also clear the count of the number of times a method was called?


From numerous other questions on SO it is said that in order to reset the count of the number of times a method call was made on a mock object you can call BackToRecord() and then Replay().

However this does not work for me. It will reset the stubbed values but not the method call count.

So extending an example from a related question...

public interface IFoo { string GetBar(); }
    [TestMethod]
    public void TestRhino()
    {
        var fi = MockRepository.GenerateStub<IFoo>();
        fi.Stub(x => x.GetBar()).Return("A");
        Assert.AreEqual("A", fi.GetBar());
        fi.AssertWasCalled(x=>x.GetBar(), x=>x.Repeat.Once());

        // Switch to record to clear behaviour and then back to replay
        fi.BackToRecord(BackToRecordOptions.All);
        fi.Replay();

        fi.Stub(x => x.GetBar()).Return("B");
        Assert.AreEqual("B", fi.GetBar());
        fi.AssertWasCalled(x => x.GetBar(), x => x.Repeat.Once());
    }

This fails on the last line with 'Expected #1, actual #2'.

Am I missing the point or does it simply not work for the method count? Is there anyway to achieve this without creating a new mock?

For reasons that I won't go into I am not able to set up expectations before making the call to GetBar().


Solution

  • Well, it doesn't work that way; it is an unusual use case.

    Here is one alternative:

    [TestMethod]
    public void TestRhino()
    {
    
        var getBarCount = 0;
    
        var fi = MockRepository.GenerateStub<IFoo>();
        fi.Stub(x => x.GetBar()).Return("A").WhenCalled(x => getBarCount++);
        Assert.AreEqual("A", fi.GetBar());
        Assert.AreEqual(1, getBarCount);
    
        // Switch to record to clear behaviour and then back to replay
        fi.BackToRecord(BackToRecordOptions.All);
        fi.Replay();
        getBarCount = 0;
    
        fi.Stub(x => x.GetBar()).Return("B").WhenCalled(x => getBarCount++);
        Assert.AreEqual("B", fi.GetBar());
        Assert.AreEqual(1, getBarCount);
    }