[英]Mocking a method that takes a delegate in RhinoMocks
I have the following classes: 我有以下课程:
public class HelperClass
{
HandleFunction<T>(Func<T> func)
{
// Custom logic here
func.Invoke();
// Custom logic here
}
// The class i want to test
public class MainClass
{
public readonly HelperClass _helper;
// Ctor
MainClass(HelperClass helper)
{
_helper = helper;
}
public void Foo()
{
// Use the handle method
_helper.HandleFunction(() =>
{
// Foo logic here:
Action1();
Action2(); //etc..
}
}
}
I want to test MainClass
only. 我只想测试
MainClass
。 I a using RhinoMocks to mock HelperClass
in my tests. 我在测试中使用RhinoMocks来模拟
HelperClass
。
The problem is, while I am not interested in testing the HandleFunction()
method I am interested in checking Action1
, Action2
and other actions that were sent to HandleFunction()
when called.. 问题是,虽然我没有兴趣在测试
HandleFunction()
方法我感兴趣的检查Action1
, Action2
和其他行动被送往HandleFunction()
调用的时候..
How can I mock the HandleFunction()
method and while avoiding it's inner logic, invoke the code that was sent to it as a parameter? 我如何模拟
HandleFunction()
方法,同时避免它的内部逻辑,调用作为参数发送给它的代码?
Because your unit under test most probably requires the delegate to be called before proceeding, you need to call it from the mock. 因为您的被测单元很可能需要在继续之前调用委托,所以您需要从模拟中调用它。 There is still a difference between calling the real implementation of the helper class and the mock implementation.
调用辅助类的实际实现和模拟实现之间仍然存在差异。 The mock does not include this "custom logic".
模拟不包括这个“自定义逻辑”。 (If you need that, don't mock it!)
(如果你需要,不要嘲笑它!)
IHelperClass helperMock = MockRepository.GenerateMock<IHelperClass>();
helperMock
.Stub(x => x.HandleFunction<int>())
.WhenCalled(call =>
{
var handler = (Func<int>)call.Argument[0];
handler.Invoke();
});
// create unit under test, inject mock
unitUnderTest.Foo();
In addition to Stefan's answer I'd like to show quite another way to define stub which invokes passed argument: 除了Stefan的回答之外,我还想展示另一种定义调用传递参数的存根的方法:
handler
.Stub(h => h.HandleFunction(Arg<Func<int>>.Is.Anything))
.Do((Action<Func<int>>)(func => func()));
Please read more about Do()
handler here and here . 请在此处和此处阅读有关
Do()
处理程序的更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.