【发布时间】: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