簡體   English   中英

模擬一個在RhinoMocks中接受委托的方法

[英]Mocking a method that takes a delegate in RhinoMocks

我有以下課程:

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()方法,同時避免它的內部邏輯,調用作為參數發送給它的代碼?

因為您的被測單元很可能需要在繼續之前調用委托,所以您需要從模擬中調用它。 調用輔助類的實際實現和模擬實現之間仍然存在差異。 模擬不包括這個“自定義邏輯”。 (如果你需要,不要嘲笑它!)

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

除了Stefan的回答之外,我還想展示另一種定義調用傳遞參數的存根的方法:

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

在此處此處閱讀有關Do()處理程序的更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM