如何将Moq用于以Func为参数的单元测试方法

时间:2016-09-23 13:44:08

标签: c# unit-testing moq

我的静态方法如下。问题是我的代码不是注入对象/类实现接口,而是使用Func作为方法参数。如何用Moq模拟它?

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;
        }
...
}   }

1 个答案:

答案 0 :(得分:2)

当将Func对象作为参数时,您可以简单地发送所需的模拟行为(当使用Moq时,您创建一个对象,然后使用模拟委托设置其行为)。

    [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");

    }