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