使用Flurl GetResponseJson <恐怖>()的单元测试代码

时间:2016-09-20 15:53:04

标签: c# unit-testing moq flurl

我正在尝试对正在捕获FlurlHttpException并调用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);
}

1 个答案:

答案 0 :(得分:2)

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