加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 模拟一个在RhinoMocks中接受委托的方法

发布时间:2020-12-15 04:15:20 所属栏目:百科 来源:网络整理
导读:我有以下课程: public class HelperClass { HandleFunctionT(FuncT func) { // Custom logic here func.Invoke(); // Custom logic here }// The class i want to test public class MainClass{ public readonly HelperClass _helper; // Ctor MainClass(He
我有以下课程:
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()方法不感兴趣,但我有兴趣检查Action1,Action2和其他在调用时发送给HandleFunction()的动作.
我如何模拟HandleFunction()方法,同时避免它的内部逻辑,调用作为参数发送给它的代码?

解决方法

因为您的被测单元很可能需要在继续之前调用委托,所以您需要从模拟中调用它.调用辅助类的实际实现和模拟实现之间仍然存在差异.模拟不包括这个“自定义逻辑”. (如果你需要,不要嘲笑它!)
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();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读