断言200 Http响应中的空内容

本文关键字:Http 响应 断言 | 更新日期: 2023-09-27 18:21:05

我有一个简单的WebApi方法,它返回一个列表。我决定,作为一个通用的项目规则,如果列表对于特定的userId是空的,我们将返回一个内容为空的Ok()方法。我的web api方法如下所示:

[Route("")]
[HttpGet]
public IHttpActionResult GetPersonalList()
{
    var result = _facade.Get(_userContext.Get());
    if (result == null)
        return Ok(); //here is the point
    return Ok(new PersonalExpensesReportViewModel(result));
}

试图对这种方法进行100%的覆盖,我想测试我提到的场景,但我无法实现如何为空内容编写断言。

[TestMethod]
public void GetPersonalList_NoContent_Ok()
{
    //Arrange
    _facade.Setup(x => x.Get(_userContext.Object.GetPersonnelNumber(), null)).Returns((PersonalExpensesReport)null);
    //Act
    var result = _controller.GetPersonalList();
    //Assert
    var negociatedResult = result as OkResult;
    Assert.IsNotNull(result);
    // ?? I want something like Assert.IsNull(negociatedResult.Content)
}

由于我没有一个特定的类型来使结果为OkNegotiatedContentResult,这需要实例化t类型,所以我考虑强制转换为OkResult,但我在这个类中没有'Content'属性

有人知道如何处理这种情况吗?

断言200 Http响应中的空内容

请尝试使用OkNegotiatedContentResult<T>,如:

var result = _controller.GetPersonalList();
var response = result as OkNegotiatedContentResult<PersonalExpensesReportViewModel>;   
Assert.IsNotNull(response);
var content = response.Content;
Assert.AreEqual(5, content.Count());
    [TestMethod]
    public void GetPersonalList_NoContent_Ok()
    {
    var serviceresponse = new yourresponseobject<yourmodel>{
    Message = "what ever response";
    Data = null;
    };
    var service = new Mock<youserviceInterface>(MockBehavior.Strict);
                service.Setup(x => x.GetPersonalList()(It.IsAny<string>())).ReturnsAsync(serviceResponse); /// for number of parameters in controller method, add It.IsAny<string>() 
        //Arrange
        _facade.Setup(x => x.Get(_userContext.Object.GetPersonnelNumber(), null)).Returns((PersonalExpensesReport)null);
        //Act
        var result = _controller.GetPersonalList();
        //Assert
        var negociatedResult = result as Object;
        Assert.IsNotNull(result.value);
Assert.AreEqual(200,result.negociatedResult.statuscode);

    }