如何从 Web Api Problem 获取返回消息?

时间:2021-07-08 01:32:31

标签: c# xunit

我的 Web Api 中有这个方法。

    [HttpPost("add", Name = "AddCampaign")]
    [ProducesResponseType(StatusCodes.Status201Created)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    [ProducesResponseType(StatusCodes.Status500InternalServerError)]
    public async Task<ActionResult<CampaignDTOResponse>> AddCampaign([FromBody] CampaignDTORequest newCampaign)
    {
        try
        {
            var campaign = _mapper.Map<Campaign>(newCampaign);
            campaign = await _campaignService.AddCampaignAsync(campaign);
            var campaignDtoResponse = _mapper.Map<CampaignDTOResponse>(campaign);
            return CreatedAtAction(nameof(GetCampaignById), new { id = campaignDtoResponse.Id }, campaignDtoResponse);
        }
        catch (Exception ex)
        {
            _logger.LogError(0, ex, ex.Message);
            return Problem(ex.Message);
        }
    }

这是我在 Xunit 中的测试。

    [Fact]
    public async Task AddCampaign_ReturnBadRequestWhenStartDateIsGreaterThanEndDate()
    {
        var client = _factory.CreateClient();
        string title = string.Format("Test Add Campaign {0}", Guid.NewGuid());
        var campaignAddDto = new CampaignDTORequest
        {
            Title = title, StartDate = new DateTime(2021, 6, 7), EndDate = new DateTime(2021, 6, 6)
        };
        var encodedContent = new StringContent(JsonConvert.SerializeObject(campaignAddDto), Encoding.UTF8, "application/json");

        var response = await client.PostAsync("/api/Campaign/add", encodedContent);

        Assert.False(response.IsSuccessStatusCode);
        Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
    }

当测试在无效日期范围内通过时,我在 Web Api 中收到验证错误消息。

enter image description here

如何在 Xunit 中获取此验证错误消息以便我可以断言它?

ProblemControllerBase 类中。

ControllerBase

1 个答案:

答案 0 :(得分:1)

根据 MSDN 上关于 Problem 的文档,它返回一个 const res = await axios.post( 'https://api.reddalerts.com/api/login', body, config ); 实例。

ObjectResult 是一个结果,它可能包含 JSON 形式的更多数据。默认情况下,它包含来自类 ProblemDetails 的数据。此外,默认状态代码将为 500。

所以在你的代码中,下面的断言可以通过

ObjectResult

要从响应中获取错误消息.. 您需要将响应正文转换为与 ProblemDetails 类具有相同结构的类对象。

Assert.False(response.IsSuccessStatusCode);
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);

然后你需要将响应体反序列化为这个类的一个对象。

public class ApiProblem
{
    public string Type { get; set; }
    public string Title { get; set; }
    public int Status { get; set; }
    public string Detail { get; set; }
    public string TraceId { get; set; }
}

然后使用对象的 var responseContent = await response.Content.ReadAsStringAsync(); var apiProblem = JsonConvert.DeserializeObject<ApiProblem>(responseContent); 属性来断言错误消息。

Detail

希望这能帮助您解决问题。

相关问题