Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test JsonResult from .NET MVC controller

The controller action being tested:

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

Test code for the controller: wondering what I need to do to test the Json being returned from the controller:

    [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);
    }
like image 351
Nick B Avatar asked Jan 20 '26 11:01

Nick B


1 Answers

I have to give credit to this post first: How do I iterate over the properties of an anonymous object in 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);

Hope this helps or at least gives you a jumping point.

like image 193
ermagana Avatar answered Jan 22 '26 03:01

ermagana