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;
}
...
} }
您是否因某种原因需要使用Moq?您可以在单元测试中简单地创建自己的Func对象。 –
任何示例?一般来说,我希望能够计算它开始的时间。我知道我可以用属性创建新类,每次启动都可以增加它。但我想使用Moq;) –
只是创建一个功能,并使用,没有需要Moq。在这个函数内,你可以计算它被调用的次数。边注。你的设计应该重构。中继器可以被重构为不必使用静态方法 – Nkosi