【问题标题】:Mocking a method that takes a delegate in RhinoMocks在 RhinoMocks 中模拟一个接受委托的方法
【发布时间】:2013-01-11 15:48:01
【问题描述】:

我有以下课程:

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..
        }
    }
}

我只想测试MainClass。我在测试中使用 RhinoMocks 模拟 HelperClass
问题是,虽然我对测试HandleFunction() 方法不感兴趣,但我有兴趣检查Action1Action2 和其他在调用时发送到HandleFunction() 的操作..
如何模拟HandleFunction() 方法,同时避免其内部逻辑,调用作为参数发送给它的代码?

【问题讨论】:

    标签: c# unit-testing rhino-mocks


    【解决方案1】:

    因为您的被测单元很可能需要在继续之前调用委托,所以您需要从模拟中调用它。调用助手类的真实实现和模拟实现还是有区别的。模拟不包括此“自定义逻辑”。 (如果需要,请不要嘲笑它!)

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

    【讨论】:

    • 另一种方法是让Func&lt;&gt; 成为您正在测试的类的一等成员(属性)。你的班级只是打电话给_helper.HandleFunction(myFunc);;您在类中提供了 myFunc 的默认实现,但将其替换为您的单元测试。
    【解决方案2】:

    除了 Stefan 的回答,我想展示另一种定义存根的方法,它调用传递的参数:

    handler
        .Stub(h => h.HandleFunction(Arg<Func<int>>.Is.Anything))
        .Do((Action<Func<int>>)(func => func()));
    

    请阅读更多关于Do()处理程序herehere的信息。

    【讨论】:

    • 谢谢!但是,此特定示例不起作用。 DO 函数中预期的委托必须返回与存根函数相同的类型(在本例中为 int)
    • 你试过了吗?在您的示例中,HanldeFunction() 什么也不返回:)。我假设,它返回void。如果 HanldeFunction() 的实际签名与我的假设不同,只需将另一个适当的 lambda 传递给 Do() 处理程序。
    猜你喜欢
    • 1970-01-01
    • 2010-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-20
    • 1970-01-01
    • 1970-01-01
    • 2017-02-21
    相关资源
    最近更新 更多