RhinoMocks mock method without return

3.6k views Asked by At

I am new to mocking. I need to mock method (it doesn't have return value). I cannot find any examples of how to mock a method. I need to mock ITempDa.Import method.

 var stub = MockRepository.GenerateStub<ITempDA>();
 stub.Stub(x => x.Import(param1)). ???


 public void MockedImport() {
    // some processing here
 }

ITempDa.Import should be mocked and instead some internal method "MockedImport" should be called.

2

There are 2 answers

0
Old Fox On BEST ANSWER

As @JamesLucas said you don't need to use Return() method(you should use this method only when your method is not void).

In this case you should use the Do() method:

var stub = MockRepository.GenerateStub<ITempDA>();
stub.Stub(x => x.Import(Arg<object>.Is.Anything))
                .Do(new Action<object>(o => MockedImport()));

or if MockedImport ths same arguments as Import:

stub.Stub(x => x.Import(Arg<object>.Is.Anything))
                .Do(new Action<object>(MockedImport);

You should use WhenCalled method when the method under test called your fake and you want to intercept the execution(execute something + change return value/change arguments/do additional steps and etc...). Another reason to use Do instead of WhenCalled is, your code become more readable.

Usually I do not recommend to use IgnoreArguments method. The reason is quite simple, you test the method behaviour. When something violate the method behaviour then the test should fail. IgnoreArguments easily hide things. However, if the calling parameters aren't important do:

stub.Stub(x => x.Import(null))
                .IgnoreArguments()
                .Do(new Action<object>(o => MockedImport()));
0
James Lucas On

In this instance you don't need a Return() call as the method is void returning. If you want to intercept the call and perform some logic on the mocked operation then use WhenCalled. In this scenario it's also worht just ignoring the arguments in the Stub and handling everything in the WhenCalled expression. e.g.

 var stub = MockRepository.GenerateStub<ITempDA>();
 stub.Stub(x => x.Import(null))
     .IgnoreArguments()
     .WhenCalled(invocation =>
     {
         var arg = invocation.Arguments[0] as ...;
         // etc
     });