Search code examples
.netmockingrhino-mocks

In Rhino Mock, how do I mock a property to it can be “call” more than once?


This should be easy, so I must be missing something (very likely as this is my first time using Rhino Mock)

I just wish my code to be able to call helm.CurrentEnterprise any number of times, but instead I get:

System.InvalidOperationException occurred
  Message=Previous method 'IHelm.get_CurrentEnterprise();' requires a return value or an exception to throw.
  Source=Rhino.Mocks
  StackTrace:
       at Rhino.Mocks.Impl.RecordMockState.AssertPreviousMethodIsClose()
       at Rhino.Mocks.Impl.RecordMockState.MethodCall(IInvocation invocation, MethodInfo method, Object[] args)
       at Rhino.Mocks.MockRepository.MethodCall(IInvocation invocation, Object proxy, MethodInfo method, Object[] args)
       at Rhino.Mocks.Impl.RhinoInterceptor.Intercept(IInvocation invocation)
       at Castle.DynamicProxy.AbstractInvocation.Proceed()
       at IHelmProxy44ecadd4f07244fd96c5849febe94a58.get_CurrentEnterprise()
       at KSS.PS3.Testing.UnitTests.ModelOptions.RuleGroupTreeViewTest.AsUsedByRuleGroupModalOptionEditor() in D:\dev\5.0.0\main\Application\Testing\Tests\UnitTests\ModelOptions\RuleGroupTreeView.cs:line 54
  InnerException:

This is my code:

   MockRepository mocks = new MockRepository();
   IHelm helm = mocks.Stub<IHelm>();
   helm.Stub(x => x.CurrentEnterprise).Return(enterprise).Repeat.Any();         

   var a2 = helm.CurrentEnterprise;
   var a2a = helm.CurrentEnterprise; // <- the exception comes from here
   var a2aa = helm.CurrentEnterprise;

Solution

  • Try out generate a Mock

    MockRepository.GenerateMock<IHelm>()
    

    Rather than Stub:

    Stub<IHelm>()
    

    The difference between stubs and mocks (Rhino Mocks online documentation)

    A mock is an object that we can set expectations on, and which will verify that the expected actions have indeed occurred. A stub is an object that you use in order to pass to the code under test. You can setup expectations on it, so it would act in certain ways, but those expectations will never be verified. A stub's properties will automatically behave like normal properties, and you can't set expectations on them