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