c# - 在 RhinoMocks 中模拟接受委托(delegate)的方法

标签 c# unit-testing rhino-mocks

我有以下类(class):

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() 方法,同时避免它的内部逻辑,调用作为参数发送给它的代码?

最佳答案

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

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

关于c# - 在 RhinoMocks 中模拟接受委托(delegate)的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14559779/

相关文章:

python - 使用 pytest-cov 的类声明缺少测试覆盖率

java - JRebel 的测试覆盖率下降了吗?

rhino-mocks - Rhino Mock 3.6 Repository 预期#0,实际#1

c# - 使用 RhinoMocks 测试私有(private)方法

c# - string1 中有多少个 string2?

c# - 如何修复 C# 中 Fortify 扫描中的 Xpath 注入(inject)问题

c# - Entity Framework Code First 从两个表和一对多关系创建类

unit-testing - Jasmine 单元测试 : $compile produces comment out of ng-repeat

java - C# 中的 Rectangle2D .outcode 等效吗?

javascript - 使用 RhinoMock 或 Moq 测试方法的内部结构