单元测试代码使用Flurl GetResponseJson()

本文关键字:TError GetResponseJson 代码 Flurl 单元测试 | 更新日期: 2023-09-27 18:07:50

我正试图对捕获FlurlHttpException并调用GetResponseJson<TError>()以获取捕获块中的错误信息的控制器进行单元测试。我试图模拟异常,但Call属性不允许我设置Settings。当单元测试运行时,它会失败,因为设置中没有JsonSerializer。我如何设置这个测试?

这是我目前的尝试,不工作:

控制器

[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);
}

单元测试代码使用Flurl GetResponseJson<TError>()

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

相关文章:
  • 没有找到相关文章