RhinoMocks mock method without return

我的梦境 提交于 2019-12-08 10:20:14

问题


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.


回答1:


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()));



回答2:


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
     });


来源:https://stackoverflow.com/questions/30845222/rhinomocks-mock-method-without-return

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!