当前位置: 首页 > 工具软件 > rEFIt > 使用案例 >

在Refit上模拟ApiException

许振海
2023-12-01

目录

介绍

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

 类似资料: