gpt4 book ai didi

c# - 使用 Flurl GetResponseJson() 的单元测试代码

转载 作者:行者123 更新时间:2023-11-30 23:20:48 25 4
gpt4 key购买 nike

我正在尝试对捕获 FlurlHttpException 的 Controller 进行单元测试并调用 GetResponseJson<TError>()在 catch block 中获取错误消息。我试图模拟异常,但是 Call属性不允许我设置 Settings .单元测试运行时失败,因为设置中没有 JsonSerializer。如何设置此测试?

这是我目前的尝试,但没有成功:

Controller

[Route]
public async Task<IHttpActionResult> Post(SomeModel model)
{
try
{
var id = await _serviceClient.Create(model);

return Ok(new { id });
}
catch (FlurlHttpException ex)
{
if (ex.Call.HttpStatus == HttpStatusCode.BadRequest)
return BadRequest(ex.GetResponseJson<BadRequestError>().Message);
throw;
}
}

单元测试

[TestMethod]
public async Task Post_ServiceClientBadRequest_ShouldReturnBadRequestWithMessage()
{
//Arrange
string errorMessage = "A bad request";
string jsonErrorResponse = JsonConvert.SerializeObject(new BadRequestError { Message = errorMessage });
var badRequestCall = new HttpCall
{
Response = new HttpResponseMessage(HttpStatusCode.BadRequest),
ErrorResponseBody = jsonErrorResponse
//This would work, but Settings has a private set, so I can't
//,Settings = new FlurlHttpSettings { JsonSerializer = new NewtonsoftJsonSerializer(new JsonSerializerSettings()) }
};

_mockServiceClient
.Setup(client => client.create(It.IsAny<SomeModel>()))
.ThrowsAsync(new FlurlHttpException(badRequestCall, "exception", new Exception()));

//Act
var result = await _controller.Post(new SomeModel());
var response = result as BadRequestErrorMessageResult;

//Assert
Assert.IsNotNull(response);
Assert.AreEqual(errorMessage, response.Message);
}

最佳答案

如果你在你的ServiceClient对象中封装了Flurl的用法,那么我认为捕获FlurlException,提取Message,并返回一个更合适的异常也应该封装在那个服务中。这将使您的 Controller 更容易测试。

关于c# - 使用 Flurl GetResponseJson<TError>() 的单元测试代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39598665/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com