简体   繁体   English

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

[英]How to use Moq to unit test method which has Func as parameter

My static method is following. 我的静态方法如下。 The problem is that my code is not injecting object/class implementing interface, but it uses Func as method parameter. 问题是我的代码没有注入对象/类的实现接口,而是使用Func作为方法参数。 How to mock it with Moq? 如何用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;
        }
...
}   }

When having a Func object as a parameter you could simply send in the wanted mock behavior (When using Moq you create an object and then set its behavior with a mock delegate). 将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");

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM