RhinoMocks 模拟方法没有返回 [英] RhinoMocks mock method without return
问题描述
我是嘲讽的新手.我需要模拟方法(它没有返回值).我找不到任何有关如何模拟方法的示例.我需要模拟 ITempDa.Import
方法.
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
应该被模拟,而应该调用一些内部方法MockedImport
".
ITempDa.Import
should be mocked and instead some internal method "MockedImport
" should be called.
推荐答案
正如@JamesLucas 所说你不需要使用 Return()
方法(你应该只在你的方法是不是 void
).
As @JamesLucas said you don't need to use Return()
method(you should use this method only when your method is not void
).
在这种情况下,您应该使用 Do()
方法:
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()));
或者如果 MockedImport
与 Import
的参数相同:
or if MockedImport
ths same arguments as Import
:
stub.Stub(x => x.Import(Arg<object>.Is.Anything))
.Do(new Action<object>(MockedImport);
当被测方法调用您的假方法并且您想拦截执行时,您应该使用 WhenCalled
方法(执行某些内容+更改返回值/更改参数/执行其他步骤等...).使用 Do
而不是 WhenCalled
的另一个原因是,您的代码变得更具可读性.
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.
通常我不推荐使用 IgnoreArguments
方法.原因很简单,您测试方法行为.当某些事情违反方法行为时,测试应该失败.IgnoreArguments
很容易隐藏东西.但是,如果调用参数不重要,请执行以下操作:
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()));
这篇关于RhinoMocks 模拟方法没有返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!