2016-09-23 52 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"); 

    } 
相关问题