How to verify calls expectations after some point using RhinoMocks

Hi guys. Few weeks ago when I was writing unit tests using RhinoMocks and NUnit I got some special test case – I needed to assert that one method of class under test calls method of another instance while test setup requires execution of code that already calls this method.

Let me give you simple example:

public class ClassUnderTest { private readonly IDataProvider dataProvider; public ClassUnderTest(IDataProvider dataProvider) { this.dataProvider = dataProvider; dataProvider.RetrieveData(); } public void MethodUnderTest() { dataProvider.RetrieveData(); } }

And here is test for MethodUnderTest:

[TestClass] public class Test { private IDataProvider dataProviderMock; private ClassUnderTest target; [TestInitialize] public void Init() { dataProviderMock = MockRepository.GenerateMock<IDataProvider>(); target = new ClassUnderTest(dataProviderMock); } [TestMethod] public void NeedToRetreiveData() { target.MethodUnderTest(); dataProviderMock.AssertWasCalled(provider => provider.RetrieveData()); } }

As you can see, test tries to verify whether MethodUnderTest calls RetrieveData method of IDataProvider instance. This test is invalid because constructor of ClassUnderTest already calls this method so it won’t verify anything.

It seems that RhinoMocks does not provide any solution to clear performed calls to mocks or maybe I wasn’t lucky to find it. I found another solution instead:

[TestMethod] public void NeedToRetreiveData() { dataProviderMock.Expect(provider => provider.RetrieveData()); target.MethodUnderTest(); dataProviderMock.VerifyAllExpectations(); }

Here I’m using Expect method instead of AssertWasCalled which works slightly differently – mocked object starts tracking of expected calls only after setup via Expect method and after code under test you need to verify your expecations using VerifyAllExpectations method.

That’s it. If you have similar test try to use approach described above. If you know how to clear history of generated mock object let me know. Thank you Smile.