在Refit上模拟ApiException

目录

介绍

Web API

测试


如何使用MockRefit来测试应用程序是否正确报告了422状态代码和字符串错误(或其他任何内容)。

介绍

我使用Refit在我的代码中调用Web API

我也喜欢在Web API必须报告应用程序中存在逻辑错误而不是异常时使用StatusCode 422并使用测试来验证代码。

所以我想在这里写下这个问题,我们如何使用MockRefit来测试应用程序是否正确报告了422状态代码和字符串错误(或其他任何内容)。

Web API

我的Web API有一个带有Response和一个Error属性的类。

public class Response
{
    public string Error { get; set; }
    public void SetError(string error)
    {
        Error = error;
    }
}

和一个refitinterface

public interface IClient
{
    [Post("/Controller/MyMethod")]
    Task MyMethod([Body]Parameters parameters);
}

工作代码可能是这样的:

public string ApiCaller(IClient client)
{
    try
    {
        await client.MyMethod
        (
            new Parameters(...);
        );
    }
    catch(ApiException ex) when (ex.StatusCode == HttpStatusCode.UnprocessableEntty)
    {
        return ex.GetContentAsync().Result.Errors
    }
    return string.Empty;
}

使用此代码,我们可以在Refit抛出ApiException。如果另一个异常是throws(500, 404 ...),就会有一个异常,我们可以用另一个catch语句或以集中的方式捕获它。

测试

我们使用MockApiException来构建模拟使用的异常:

public static MockApiException
{
    public static ApiException CreateApiException(HttpStatusCode statusCode, T content)
    {
        var refitSettings = new RefitSettings;
        return ApiException.Create(null, null, 
            new HttpResponseMessage
            {
                StatusCode = statusCode,
                Content = refitSettings.ContentSerializer.ToHttpContent(content)
            }, refitSettings).result;
    }
}

我们可以Mock客户端并使用MockApiException来构建模拟将抛出的异常。

var response = new Response("Error thrown by web api")
var mockClient = new Mock();
mockClient.Setup(x => x.MyMethod(
    It.Is(...)
))
.Thrown(MockApiException.CreateApiException(HttpStatusCode.UnprocessableEntity, response);

现在可以测试一下,当我们调用ApiCallerrefit抛出422异常时,结果等于错误。

var result = ApiCaller(mockClient.Object);  
Assert.That(result == "Error thrown by web api");

https://www.codeproject.com/Tips/5312309/Mock-ApiException-on-Refit

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值