2

我正在尝试对捕获 aFlurlHttpException并调用GetResponseJson<TError>()以获取 catch 块中的错误消息的控制器进行单元测试。我试图模拟异常,但该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);
}
4

1 回答 1

2

如果您在 ServiceClient 对象中封装了 Flurl 的使用,那么我认为捕获 FlurlException、提取消息并返回更合适的异常也应该封装在该服务中。这将使您的控制器更容易测试。

于 2016-09-21T02:59:19.277 回答