c# - 使用 Nsubstitute 模拟 RestClient ExecuteAsync

标签 c# unit-testing restsharp nsubstitute

尝试使用 Nsubstitute 模拟 RestClient(来自 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 从未设置。这里有人知道如何实现这项工作吗?

编辑:已解决。谢谢恩科西。所以我只是按照下面的解释对其进行了更新,并且没有返回。如果我更仔细地阅读文档,我就会看到 David Tchepak 在评论中提到的部分。

最佳答案

从最初的检查来看,您似乎没有对传递到模拟方法中的回调操作执行任何操作

RestClientMock
    .ExecuteAsync(
        Arg.Any<IRestRequest>(), 
        Arg.Do<Action<IRestResponse, RestRequestAsyncHandle>>(callback => 
            callback(new RestResponse { StatusCode = HttpStatusCode.NotFound}, null))
    )

关于c# - 使用 Nsubstitute 模拟 RestClient ExecuteAsync,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47624222/

相关文章:

C# 引用数组

c# - 我可以将 DynamicParameters 与模板一起使用并在 dapper 中有一个返回参数吗?

python - 如何为 python 单元测试模拟 mongodb?

c# - 如何从 docusign 检索已签名的用户文档?

c# - 以字符串形式返回响应

c# - RestClient - 请求返回 500 内部服务器错误(内容为 html)并且没有 ErrorMessage

c# - A a =new A() 和 A a=null 的区别

c# - 如何签署 Visual Studio .msi 的安装文件

java - 将 PowerMock 与嵌入式 Tomcat 结合使用

ruby - 使单元测试快速失败以进行突变测试