c# - 如何对 Refit ApiResponse<T> 进行单元测试?

标签 c# rest unit-testing refit

我使用 refit 来调用 API,响应包含在 ApiResonse<T> 中。我可以模拟返回模拟 ApiResponse<T> 的 refit 调用并断言。一切都按预期工作,只是我不确定如何测试返回异常的 api 调用。

[Get("/customer/{id}")]
Task<ApiResponse<Customer>> GetCustomer(int id);

看起来如果ApiResponse<T>使用 Refit 将请求内部发生的所有异常包装到 ApiException 中并附加到ApiResponse<T> 。如果Task<T>而是使用,捕获 ApiException是调用者的责任。

我创建了ApiExceptionApiException.Create()但不确定将其放在 ApiResponse<T> 中的哪个位置。 Create()的最后一个参数方法是 ApiException 但我创建和设置的异常根本没有显示在 ApiResponse 中,因此无法测试。

var apiResponse = new ApiResponse<Customer>(
    new HttpResponseMessage(BadRequest),
    null,
    null,
    await ApiException.Create(,,,Exception("Something bad happened inside the api")
 );

我无法获取 Something bad happened...单元测试中的消息,但只是“错误请求”消息。我是否在 retrofit 中对 ApiResponse 进行单元测试?任何帮助是极大的赞赏。谢谢

最佳答案

我不知道 Refit,但根据他们的文档,我期望以下两个选项:

返回ApiResponse<Customer>

让我们看一下您的代码(顺便说一句,这不是正确的 C# - 请提供正确工作的代码):

var apiResponse = new ApiResponse<Customer>(
    new HttpResponseMessage(BadRequest),
    null,
    null,
    await ApiException.Create(,,,Exception("Something bad happened inside the api")
 );

执行此代码时,Refit 会被指示准确返回您所要求的内容:return HTTP 500有以下内部异常

所以我希望您会在 apiResponse.Error 中发现API 内部发生了一些不好的事情 ,但不会抛出异常。

抛出ApiException

ApiException源自System.Exception ,你可以替换这个

var apiResponse = new ApiResponse<Customer>(
    new HttpResponseMessage(BadRequest),
    null,
    null,
    await ApiException.Create(,,,Exception("Something bad happened inside the api")
 );

throw await ApiException.Create("Something bad happened inside the api", message, method, response, settings);

现在您可以在单元测试中捕获异常。

关于c# - 如何对 Refit ApiResponse<T> 进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72355253/

相关文章:

wcf - 用于测试 WCF Rest 服务的测试客户端还是仅使用浏览器?

php - 如何模拟对象属性?

unit-testing - 在没有 Controller 的情况下测试电子邮件发送

c# - 如何不限制 maxBufferSize 和 maxReceivedMessageSize

c# - 如何强制对集合中的所有元素进行错误验证?

php - resource.create 和 resource.store 之间的 Laravel 区别

.net - 在 F# 中使用 MSTest

javascript - 如何根据url参数返回部分页面

c# - 将两个 datagridview 列合并为一个新列

api - Codeigniter REST CSV 导入到 mysql