如何在asp.net web api中测试NotFound http状态

时间:2016-11-23 09:04:22

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

我试图编写一个测试用例来检查我的操作方法是否返回404状态代码。

所以这里是我的Web Api Action Method

[Route("{username}/{startDate}/{endDate}")]
[HttpGet]
public IHttpActionResult BulkTrackEventsByDateRange(string username, string startDate, string endDate)
{
    BulkEventTrackingResultModel bulkTrackingEventResult = null;
    try
    {
        bulkTrackingEventResult = _bulkTrackingByDateRange.GetBulkTrackingEvents(username, startDate, endDate);
        if (string.IsNullOrWhiteSpace(bulkTrackingEventResult.NoRecordFound))
        {
            return Ok(bulkTrackingEventResult.BulkEventTracking);
        }
        else
        {
            return Content(HttpStatusCode.NotFound, "Some Message");
        }
    }
    catch (Exception ex)
    {
        return new ResponseMessageResult(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Some Message"));
    }
}

我的测试方法是

[TestMethod]
public void BulkTrackEventsByDateRange()
{
    //Given: Username as 'Stamps' and startDate 1 months old date and endDate as yesterday's date
    string username = "Stamps";
    string startDate = DateTime.Now.AddMonths(-1).Date.ToString("MM-dd-yyyy");
    string endDate = DateTime.Now.AddDays(-1).Date.ToString("MM-dd-yyyy");
    // When: I call TrackingEventApiController object (url: /Stamps/09-22-2016/09-22-2016)
    List<BulkEventTrackingRepositoryModel> trackingEvent = new List<BulkEventTrackingRepositoryModel>();
    BulkEventTrackingResultModel trackingEventResult = new BulkEventTrackingResultModel
    {
        ErrorMessage = string.Empty,
        NoRecordFound = "No records found for the given date range.",
        BulkEventTracking = trackingEvent
    };
    _mockBulkTrackingByDateRange.Setup(x => x.GetBulkTrackingEvents(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(trackingEventResult);
    IHttpActionResult actionResult = _trackingEventController.BulkTrackEventsByDateRange(username, startDate, endDate);
    var contentResult = actionResult as NotFoundResult;
    // Then: 
    Assert.IsNotNull(contentResult);
}

但我的问题是行

var contentResult = actionResult as NotFoundResult;

不会将其强制转换为NotFoundResult,因此输出始终为null。

如何修复测试用例?

1 个答案:

答案 0 :(得分:1)

该操作未在该用例中返回NotFoundResult,而是返回NegotiatedContentResult<T>。这就是演员导致null的原因。好消息是NegotiatedContentResult<T>具有HttpStatusCode StatusCode { get; }属性,可用于检查结果的状态。

更新测试以期待NegotiatedContentResult<string>

//...other code removed for brevity
var contentResult = actionResult as NegotiatedContentResult<string>;
// Then: 
Assert.IsNotNull(contentResult);
Assert.AreEqual(HttpStatusCode.NotFound, contentResult.StatusCode);

并且测试应该按预期运行。