断言200 Http Response中的空内容

时间:2015-11-06 17:36:10

标签: c# unit-testing asp.net-web-api moq

我有一个简单的Web Api方法,它返回一个列表。我决定作为一般项目规则,如果列表对于特定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,但我没有此课程中的“内容”属性

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

2 个答案:

答案 0 :(得分:0)

请尝试使用OkNegotiatedContentResult<T>之类的:

var result = _controller.GetPersonalList();
var response = result as OkNegotiatedContentResult<PersonalExpensesReportViewModel>;   
Assert.IsNotNull(response);
var content = response.Content;
Assert.AreEqual(5, content.Count());

答案 1 :(得分:0)

    [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);


    }