2016-09-23 51 views
0

我的靜態方法如下。問題是我的代碼不是注入對象/類實現接口,而是使用Func作爲方法參數。如何用Moq嘲笑它?如何使用Moq以Func爲參數的單元測試方法

public class Repeater 
    { 
     const int NumberOfReapetsWithException = 5; 

     public static async Task<string> RunCommandWithException(Func<string, Task<string>> function, string parameter, 
      ILoggerService logger = null, string messageWhileException = "Exception while calling method for the {2} time", bool doRepeatCalls = false) 
     { 
      int counter = 0; 
      var result = ""; 

      for (; true;) 
      { 
       try 
       { 
        result = await function(parameter); 
        break; 
       } 
       catch (Exception e) 
       { 
        if (doRepeatCalls) 
        { 
         string message = HandleException<string, string>(parameter, null, logger, messageWhileException, ref counter, e); 

         if (counter > NumberOfReapetsWithException) 
         { 
          throw; 
         } 
        } 
        else 
        { 
         throw; 
        } 
       } 
      } 
      return result; 
     } 
... 
} } 
+4

您是否因某種原因需要使用Moq?您可以在單元測試中簡單地創建自己的Func對象。 –

+0

任何示例?一般來說,我希望能夠計算它開始的時間。我知道我可以用屬性創建新類,每次啓動都可以增加它。但我想使用Moq;) –

+1

只是創建一個功能,並使用,沒有需要Moq。在這個函數內,你可以計算它被調用的次數。邊注。你的設計應該重構。中繼器可以被重構爲不必使用靜態方法 – Nkosi

回答

2

有Func鍵對象,你可以簡單地在想仿製品的行爲發送(當使用最小起訂量創建一個對象,然後設置其行爲與模擬委託)參數時。

[TestCase] // using nunit 
    public void sometest() 
    { 
     int i = 0; 
     Func<string, Task<string>> mockFunc = async s => 
     { 
      i++; // count stuff 
      await Task.Run(() => { Console.WriteLine("Awating stuff"); }); 
      return "Just return whatever"; 
     }; 
     var a = Repeater.RunCommandWithException(mockFunc, "mockString"); 

    } 
相關問題