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

Pav*_*rno 6 c# unit-testing rhino-mocks

我有以下课程:

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..
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我只想测试MainClass.我HelperClass在测试中使用RhinoMocks进行模拟.
问题是,虽然我不感兴趣测试HandleFunction()我感兴趣的方法Action1,Action2以及HandleFunction()调用时发送的其他操作.
我如何模拟HandleFunction()方法,同时避免它的内部逻辑,调用发送到的代码它作为参数?

Ste*_*ger 6

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

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();
Run Code Online (Sandbox Code Playgroud)

  • 另一种方法是将`Func <>`作为你正在测试的类的第一类成员(属性).你的类只调用`_helper.HandleFunction(myFunc);`; 您在类中提供了myFunc的默认实现,但将其替换为单元测试. (2认同)