使用Nsubstitute尝试使用RestClient(From RestSharp)模拟ExecuteAsync方法时遇到了困难。我已经看到了一个使用Moq的示例(这里:Mocking Restsharp executeasync method using moq)但是在我的生活中不能理解为什么以下代码使用nsubstitute失败:
RestClientMock.When(x => x.ExecuteAsync(Arg.Any<IRestRequest>(), Arg.Any<Action<IRestResponse>>()))
.Do(x => new RestResponse { StatusCode = HttpStatusCode.NotFound });
我是如何设置的,然后就会按照这样的方式测试代码:
var tcs = new TaskCompletionSource<SendEmailResponse>();
_restClient.ExecuteAsync(_restRequest, (restResponse) => {
if (restResponse.StatusCode != HttpStatusCode.OK)
tcs.SetResult(new SendEmailResponse(ResponseType.Error, restResponse));
else if (!_enableEmails)
tcs.SetResult(new SendEmailResponse(ResponseType.EmailsTurnedOff, restResponse));
else
tcs.SetResult(new SendEmailResponse(ResponseType.Sent, restResponse));
});
return tcs.Task;
似乎永远不会在模拟中执行我的回调代码而只是挂起,因为tcs永远不会被设置。这里有人知道如何使这项工作吗?
编辑:已解决。谢谢Nkosi。所以我只是按照下面的说明进行新的修改,而不是返回。如果我更仔细地阅读文档,我已经看过David Tchepak在评论中提到的部分。答案 0 :(得分:3)
从初始检查开始,您似乎没有对传递给模拟方法的回调操作做任何事情
RestClientMock
.ExecuteAsync(
Arg.Any<IRestRequest>(),
Arg.Do<Action<IRestResponse, RestRequestAsyncHandle>>(callback =>
callback(new RestResponse { StatusCode = HttpStatusCode.NotFound}, null))
)
答案 1 :(得分:1)
ExecuteAsync
的功能签名是:
RestRequestAsyncHandle ExecuteAsync(IRestRequest request, Action<IRestResponse, RestRequestAsyncHandle> callback);
使用调用序列:
RestClientMock.When(x => x.ExecuteAsync(Arg.Any<IRestRequest>(), Arg.Any<Action<IRestResponse>>()))
.Do(x => new RestResponse { StatusCode = HttpStatusCode.NotFound });
你完全覆盖原来的ExecuteAsync
函数,它是使用回调的被调用函数的实现,但你的替换实现根本不使用回调!
我的建议是在ExecuteTaskAsync
函数中使用async
:
var restResponse = await _restClient.ExecuteTaskAsync(_restRequest);
if (restResponse.StatusCode != HttpStatusCode.OK)
return new SendEmailResponse(ResponseType.Error, restResponse);
else if (!_enableEmails)
return new SendEmailResponse(ResponseType.EmailsTurnedOff, restResponse);
else
return new SendEmailResponse(ResponseType.Sent, restResponse);
之后,您应该可以模拟函数ExecuteTaskAsync
。