如何从.NET MVC控制器测试JsonResult

本文关键字:控制器 测试 JsonResult MVC NET | 更新日期: 2023-09-27 18:24:11

正在测试的控制器动作:

    [AuthorizeUser]
    [HttpPost]
    [ValidateJsonAntiForgeryToken]
    public ActionResult EventDetails(int eventId)
    {
        string details = this._eventDataProvider.GetById(eventId).Comments;
        if (string.IsNullOrEmpty(details))
            details = "This location has not entered any comments or further details for this event.";
        return Json(new
        {
            details = details
        });
    }

控制器的测试代码:想知道我需要做什么来测试从控制器返回的Json:

    [TestMethod]
    public void DetailsAreReturned()
    {
        // Arrange
        eventsController = new EventsController(eventDataProvider.Object, playerEventDataProvider.Object, userDataProvider.Object,
                                                tokenAuthent.Object, dataContext.Object, customerLocationDataProvider.Object);
        eventDataProvider.Setup(x => x.GetById(1)).Returns(new Event() { Comments = "test" });
        // Act
        JsonResult result = (JsonResult) eventsController.EventDetails(1);
        // Assert
        Assert.IsNotNull(result.Data);
        Assert.AreEqual(??, result);
    }

如何从.NET MVC控制器测试JsonResult

我必须首先赞扬这篇文章:我如何在C#中迭代匿名对象的属性?

var result = new JsonResult{ Data = new {details = "This location has not entered any comments or further details for this event."}};
var det = result.Data.GetType().GetProperty("details", BindingFlags.Instance | BindingFlags.Public);
var dataVal = det.GetValue(result.Data, null);

希望这能帮助你,或者至少给你一个跳跃点。