我已经模拟了异步函数,但是每当我调用模拟函数时,它都会返回空值。
我具有如下所示的异步功能
public async Task<TResult> InvokeAzureFunctionWithTokenGetResultAsync<TArg, TResult>(TArg arg, string functionUri, string resourceid, CancellationToken canceltoken)
我想编写xUnit测试用例,因为我无法执行实际功能,因此我试图对其进行模拟。执行时没有错误,但是调用函数时,我得到的是空。
实际功能
public async Task<TResult> InvokeAzureFunctionWithTokenGetResultAsync<TArg, TResult>(TArg arg, string functionUri, string resourceid, CancellationToken canceltoken)
{
// some external code here
if (message != null && (message.StatusCode == HttpStatusCode.OK || message.StatusCode == HttpStatusCode.Created))
{
try
{
return JsonConvert.DeserializeObject<TResult>(await message.Content.ReadAsStringAsync().ConfigureAwait(true));
}
catch (JsonReaderException re)
{
throw new FormatException(re.Message, re);
}
catch (FormatException fe)
{
throw new FormatException(fe.Message, fe);
}
}
else if (message != null)
{
throw new FormatException(message.ReasonPhrase);
}
return default(TResult);
}
测试功能
IHttpEndpointInvoker httpEndpointInvoker = new HttpEndpointInvoker();
IHttpEndpointInvoker httpEndpointInvoker = new HttpEndpointInvoker();
try
{
var mock = new Mock<IHttpEndpointInvoker>();
var obj = (new RouteDefinition() { Id = routeDefinitionId, IoTHubId = "" });
mock.Setup(s => s.InvokeAzureFunctionWithTokenGetResultAsync<RouteDefinition, string>(It.IsIn<RouteDefinition>(), It.IsAny<string>(), It.IsAny<string>(), new CancellationTokenSource().Token)).Returns(Task.Factory.StartNew(() => GetHttpResponseMessage(HttpStatusCode.Accepted).Result));
var o1 = mock.Object.InvokeAzureFunctionWithTokenGetResultAsync<RouteDefinition, string>(obj, "functionUri", "resourceid", new CancellationTokenSource().Token).GetAwaiter().GetResult(); // this line is returning null. But I am expecting value that is returned by "GetHttpResponseMessage" function
}
catch (Exception ex)
{
throw;
}
注意:已成功调用“ GetHttpResponseMessage”并返回一个字符串。我已经调试了。
请检查上面代码中给出的带有以下注释的行,以获取预期的输出/结果。
//此行返回null。但我期望“ GetHttpResponseMessage”函数返回的值