【问题标题】:How to use Moq to unit test method which has Func as parameter如何使用 Moq 对以 Func 为参数的方法进行单元测试
【发布时间】:2016-09-23 13:44:08
【问题描述】:

我的静态方法如下。问题是我的代码没有注入对象/类实现接口,而是使用 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;
        }
...
}   }

【问题讨论】:

  • 出于某种原因您必须使用起订量吗?您可以简单地在单元测试中创建自己的 Func 对象。
  • 有什么例子吗?一般来说,我希望能够计算它开始了多少时间。我知道我可以创建具有属性的新类,该属性可以在每次启动时递增:)。但我想使用起订量;)
  • 只需创建一个功能并使用,不需要起订量。在函数中,您可以计算它被调用的次数。边注。你的设计应该被重构。中继器可以重构为不必使用静态方法

标签: c# unit-testing moq


【解决方案1】:

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

    }

【讨论】:

    猜你喜欢
    • 2012-06-01
    • 2021-10-15
    • 1970-01-01
    • 2020-09-06
    • 2011-01-30
    • 2023-04-04
    • 2017-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多